C. Tyler and Strings
阿新 • • 發佈:2022-03-08
C. Tyler and Strings
1.思路
對於矩陣中的每一個元素\((i,j)\),假設它在前\(i - 1\)行出現\(q\)次,在前\(j - 1\)列出現\(p\)次,產生的總貢獻為:
\[q * x_i - \sum_{k = 1}^{q}{x_k} + p * y_i - \sum_{k = 1}^{p}{y_k} \]所以我們只需要預處理出下標的字首和與當前數的出現次數就行
#include <bits/stdc++.h> #define PII pair<int,int> #define LL long long #define fi first #define se second #define debug(a) cout<<#a<<"="<<a<<endl; #define all(x) (x).begin(),(x).end() #define pb push_back #define sz(x) (int)x.size() using namespace std; int b[100010]; void solve() { int n, m; cin >> n >> m; int g[n + 5][m + 5]; LL ans = 0; map<int,LL>x, y; for(int i = 1; i <= n; i ++ ){ for(int j = 1; j <= m; j ++ ){ int t; cin >> t; g[i][j] = t; ans += i *1ll* b[t] - x[t]; x[t] += i; b[t] ++; } } memset(b, 0, sizeof b); for(int j = 1; j <= m; j ++ ){ for(int i = 1; i <= n; i ++ ){ int t = g[i][j]; ans += j *1ll* b[t] - y[t]; y[t] += j; b[t] ++; } } cout << ans << endl; } int main() { int test = 1; // scanf("%d",&test); while(test -- ) { solve(); } return 0; }