感觉是个处理平方期望的套路题。。
看题解就好啦。
https://codeforces.com/blog/entry/68111
#include<bits/stdc++.h> #define LL long long #define LD long double #define ull unsigned long long #define fi first #define se second #define mk make_pair #define PLL pair<LL, LL> #define PLI pair<LL, int> #define PII pair<int, int> #define SZ(x) ((int)x.size()) #define ALL(x) (x).begin(), (x).end() #define fio ios::sync_with_stdio(false); cin.tie(0); using namespace std; const int N = 2e5 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-10; const double PI = acos(-1); template<class T, class S> inline void add(T &a, S b) {a += b; if(a >= mod) a -= mod;} template<class T, class S> inline void sub(T &a, S b) {a -= b; if(a < 0) a += mod;} template<class T, class S> inline bool chkmax(T &a, S b) {return a < b ? a = b, true : false;} template<class T, class S> inline bool chkmin(T &a, S b) {return a > b ? a = b, true : false;} mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int power(int a, int b) { int ans = 1; while(b) { if(b & 1) ans = 1LL * ans * a % mod; a = 1LL * a * a % mod; b >>= 1; } return ans; } int n, l[N], r[N]; int p[N], q[N]; int pre[N]; int main() { scanf("%d", &n); for(int i = 1; i <= n; i++) { scanf("%d", &l[i]); } for(int i = 1; i <= n; i++) { scanf("%d", &r[i]); r[i]++; } q[1] = 0; p[1] = 1; for(int i = 1; i <= n; i++) { int L = max(l[i], l[i - 1]); int R = min(r[i], r[i - 1]); if(R > L) { q[i] = 1LL * (R - L) * power(r[i] - l[i], mod - 2) % mod * power(r[i - 1] - l[i - 1], mod - 2) % mod; } p[i] = (1 - q[i] + mod) % mod; } for(int i = 1; i <= n; i++) { pre[i] = (pre[i - 1] + p[i]) % mod; } int ans = 0; // i == j for(int i = 1; i <= n; i++) { add(ans, p[i]); } // abs(j - i) > 1 for(int i = 1; i <= n; i++) { if(i - 2 >= 1) { add(ans, 2LL * p[i] * pre[i - 2] % mod); } } r[0] = -inf; l[0] = inf; // abs(j - i) == 1 for(int i = 1; i < n; i++) { int ret = ((1 - q[i] - q[i + 1]) % mod + mod) % mod; int R = min(r[i - 1], min(r[i], r[i + 1])); int L = max(l[i - 1], max(l[i], l[i + 1])); int tmp = 0; if(R > L) { tmp = R - L; tmp = 1LL * tmp * power(r[i - 1] - l[i - 1], mod - 2) % mod; tmp = 1LL * tmp * power(r[i] - l[i], mod - 2) % mod; tmp = 1LL * tmp * power(r[i + 1] - l[i + 1], mod - 2) % mod; } add(ret, tmp); add(ans, 2LL * ret % mod); } printf("%d ", ans); return 0; } /* */