大意:给定n*m矩阵, 初始位置(r,c), 每一步随机移动到权值小于当前点的位置, 得分为移动距离的平方, 求得分期望.
直接暴力dp的话复杂度是O(n^4), 把距离平方拆开化简一下, 可以O(n^2logn).
#include <iostream> #include <sstream> #include <algorithm> #include <cstdio> #include <math.h> #include <set> #include <map> #include <queue> #include <string> #include <string.h> #include <bitset> #define REP(i,a,n) for(int i=a;i<=n;++i) #define PER(i,a,n) for(int i=n;i>=a;--i) #define hr putchar(10) #define pb push_back #define lc (o<<1) #define rc (lc|1) #define mid ((l+r)>>1) #define ls lc,l,mid #define rs rc,mid+1,r #define x first #define y second #define io std::ios::sync_with_stdio(false) #define endl ‘\n‘ #define DB(a) ({REP(__i,1,n) cout<<a[__i]<<‘ ‘;hr;}) using namespace std; typedef long long ll; typedef pair<int,int> pii; const int P = 1e9+7, P2 = 998244353, INF = 0x3f3f3f3f; ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;} ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;} ll inv(ll x){return x<=1?1:inv(P2%x)*(P2-P2/x)%P2;} inline int rd() {int x=0;char p=getchar();while(p<‘0‘||p>‘9‘)p=getchar();while(p>=‘0‘&&p<=‘9‘)x=x*10+p-‘0‘,p=getchar();return x;} //head const int N = 1e3+10; int n, m, r, c, cnt; struct _ { int x,y,w; bool operator < (const _ &rhs) const { return w<rhs.w; } } a[N*N]; int dp[N][N]; int main() { scanf("%d%d", &n, &m); REP(i,1,n) REP(j,1,m) { int t; scanf("%d", &t); a[++cnt] = {i,j,t}; } sort(a+1,a+1+cnt); a[cnt+1].w=-1; ll sum_dp = 0, sum_2 = 0, sum_x = 0, sum_y = 0; REP(R,1,cnt) { int L = R; while (a[R].w==a[R+1].w) ++R; if (L!=1) { REP(i,L,R) { ll t = (sum_dp+sum_2-a[i].x*sum_x-a[i].y*sum_y+(L-1)*((ll)a[i].x*a[i].x+(ll)a[i].y*a[i].y))%P2; t = t*inv(L-1)%P2; if (t<0) t += P2; dp[a[i].x][a[i].y] = t%P2; } } REP(i,L,R) { (sum_dp += dp[a[i].x][a[i].y]) %= P2; (sum_2 += (ll)a[i].x*a[i].x+(ll)a[i].y*a[i].y) %= P2; (sum_x += 2*a[i].x) %= P2; (sum_y += 2*a[i].y) %= P2; } } scanf("%d%d", &r, &c); printf("%d\n", dp[r][c]); }
原文地址:https://www.cnblogs.com/uid001/p/10913537.html
时间: 2024-11-06 21:32:17