E - Christmas Color Grid 1
https://atcoder.jp/contests/abc334/tasks/abc334_e
思路
https://www.cnblogs.com/Lanly/p/17923753.html
Code
https://atcoder.jp/contests/abc334/submissions/49243194
int h,w; bool s[1005][1005]; int c[1005][1005]; // c - class long long modbase = 998244353; struct NODE{ int x; int y; }; vector<struct NODE> directions = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} }; void dfs(int i, int j, int class_order){ if (i<1 || i>h){ return; } if (j<1 || j>w){ return; } bool sij = s[i][j]; if (sij == false){ return; } if (c[i][j] > 0){ return; } c[i][j] = class_order; for(int k=0; k<directions.size(); k++){ struct NODE nd = directions[k]; int ni = i + nd.x; int nj = j + nd.y; // cout << "ni = " << ni << ", nj=" << nj << endl; dfs(ni, nj, class_order); } } int get_nb_comp_num(int i, int j){ if (i<1 || i>h){ return 0; } if (j<1 || j>w){ return 0; } bool sij = s[i][j]; if (sij == true){ return 0; } set<int> nbs; for(int k=0; k<directions.size(); k++){ struct NODE nd = directions[k]; int ni = i + nd.x; int nj = j + nd.y; if (ni >= 1 && ni <=h && nj >= 1 && nj <= w){ bool sninj = s[ni][nj]; if (sninj == true){ nbs.insert(c[ni][nj]); } } } return nbs.size(); } long long qpower(long long a, long long b) { long long qwq = 1; while (b) { if (b & 1) qwq = qwq * a % modbase; a = a * a % modbase; b >>= 1; } return qwq; } long long inv(long long x) { return qpower(x, modbase - 2); } int main() { cin >> h >> w; for(int i=1; i<=h; i++){ for(int j=1; j<=w; j++){ char ch; cin >> ch; if (ch == '#'){ s[i][j] = true; } else { s[i][j] = false; } } } // cout << "--- after input ------" << endl; int class_order = 0; for(int i=1; i<=h; i++){ for(int j=1; j<=w; j++){ bool sij = s[i][j]; if (sij == true && c[i][j] == 0){ // cout << "i = " << i << ", j=" << j << endl; class_order++; dfs(i, j, class_order); } } } // for(int i=1; i<=h; i++){ // for(int j=1; j<=w; j++){ // int cij = c[i][j]; // cout << cij << " "; // } // cout << endl; // } // cout << "--- after dfs ------" << endl; long long redcnt = 0; long long compcnt = 0; for(int i=1; i<=h; i++){ for(int j=1; j<=w; j++){ bool sij = s[i][j]; if (sij == false){ // cout << "comp cnt for i=" << i << ", j=" << j << endl; redcnt++; int nbcmpnum = get_nb_comp_num(i, j); // cout << "nbcmpnum = " << nbcmpnum << endl; compcnt += class_order - nbcmpnum + 1; } } } // cout << "--- after compcnt ------" << endl; // // cout << "compcnt = " << compcnt << ", redcnt=" << redcnt << endl; // long long ret = compcnt / redcnt; long long ret = compcnt % modbase * inv(redcnt) % modbase; cout << ret << endl; return 0; }
标签:return,Color,long,int,Grid,sij,1005,Christmas From: https://www.cnblogs.com/lightsong/p/17962121