Black and white(并查集的特殊使用

链接: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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值