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

被折叠的 条评论
为什么被折叠?



