链接:https://ac.nowcoder.com/acm/contest/11254/B
来源:牛客网
题目描述
Goodeat has a white chessboard with n rows and m columns.
Each grid (i, j) has a weight c(i, j). At any time, the grid (i, j) can be dyed black at the cost of c(i, j).
Goodeat has a special talent. For the four intersecting squares of any two rows and two columns, if three of them are black squares, Goodeat can dye the fourth square black without any cost.
Please find out the minimum cost of dyeing a black chessboard.
Due to the large number of grids, we use the following method to generate weights:
A0 = a
A(i+1) = (Ai * Ai * b + Ai * c + d)% p
Where A(m*(i-1)+j) is the cost c(i, j) of the grid in the i-th row and j-th column (1≤i≤n,1≤j≤m)
解题思路:
使用并查集,创建数组root[n+m]
#include <bits/stdc++.h>
#define fo(a,b,c) for(int a=b;a<c;a++)
using namespace std;
typedef long long ll;
vector<int>oo[100000];
int root[10005];
int Root(int n){ return n==root[n]?n:root[n]=Root(root[n]);}
int main() {
int n,m,a,b,c,d,p,cnt=0,ans=0;
cin>>n>>m>>a>>b>>c>>d>>p;
fo(i,1,n+m+1) root[i]=i;
fo(i,1,n*m+1){
a=((ll)a*a*b+(ll)a*c+d)%p;
oo[a].push_back(i);
}
fo(i,0,p){
if(oo[i].empty()) continue;
for(int &k:oo[i]){
int nn=(k-1)/m+1,mm=k%m+1;
int u=Root(nn),v=Root(mm+n);
if(u!=v){
cnt++;
root[u]=v;
ans+=i;
if(cnt==n+m-1){ cout<<ans<<endl; return 0;}
}
}
}
return 0;
}