2021牛客多校第三场 B——Black and white

本文介绍了一种解决二维矩阵填充问题的方法,利用并查集数据结构来追踪已填充区域,确保在满足特定条件时自动填充剩余角,通过维护成本最小路径实现最小花费。代码展示了如何初始化并查集,合并元素,以及计算最小总成本的过程。

题目大意

给你一个 n×mn \times mn×m 的矩形,每填一个格子都有一个花费,当你把一个矩形四个角中任意三个角填上了,另外一个角自动填上,问你最小花费是多少

解题思路

首先我们肯定是从花费小的开始填,我们可以维护一个并查集。当一个点被填上之后,把这个点所在的行列都加入到一个并查集中。当我们要填一个点的时候,如果这个点的行列在同一个并查集中,说明这个点是可以自动被填上的。

Code

#include <bits/stdc++.h>
#define ll long long
#define qc ios::sync_with_stdio(false); cin.tie(0);cout.tie(0)
#define fi first
#define se second
#define PII pair<int, int>
#define PLL pair<ll, ll>
#define pb push_back
using namespace std;
const int MAXN = 5007;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const ll mod = 1e9 + 7;
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
    while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
    return x*f;
}
vector<PII> v[100007];
int n, m, a, b, c, d, p;
int fa[MAXN << 2];
void init(){
	for(int i = 0; i <= MAXN * 2; i++){
		fa[i] = i;
	}
}
int find(int x){
	return x == fa[x] ? x : fa[x] = find(fa[x]);
}
void merge(int x, int y){
	x = find(x);
	y = find(y);
	if(x != y)
		fa[y] = x;
}
void solve(){
    cin >> n >> m >> a >> b >> c >> d >> p;
	ll cost = a;
	init();
	int cnt = 0;
	for(int i = 1; i <= n; ++i)
		for (int j = 1; j <= m; ++j){
			cost = ((1ll * cost * cost % p * b % p + 1ll * c * cost % p) % p + d) % p;
			v[cost].pb({i, j+n});
		}
	ll ans = 0;
	for(int i = 0; i <= p; i++){
		for(auto [x, y] : v[i]){
			if(find(x) == find(y))
				continue;
			merge(x, y);
			ans += i;
		}
	}
	cout << ans << endl;
}

int main()
{
    #ifdef ONLINE_JUDGE
    #else
       freopen("in.txt", "r", stdin);
       freopen("out.txt", "w", stdout);
    #endif

    qc;
    int T;
    // cin >> T;
    T = 1;
    while(T--){

        solve();
    }
    return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值