题意:给你n*m的矩阵,如果将一个矩形的四个角中的三个变成黑色,那么第四个角也会变成黑色,问将矩阵全部涂黑最少需要多少代价
思路:用最小生成树,把矩阵的行列设为点,行列对应着无向边,如果一个点的行列都在并查集当中,那么就不用考虑这个点的贡献的,也就相当于把这n+m个点连起来
用Prim,时间复杂度是O(n²);用kruskal,时间复杂度是O(mlogm)
所以用Prim,kruskal会超时,泪目
要有把这道题转化为最小生成树的能力,首先想到只需要找到n+m个点,每一行每一列都要有,进而想到把行列转化为边的两个端点
代码:
//主要是Kruskal算法复杂度mlogm,放到这道题就是n*mlognm
//prim是n2,所以放到这道题prim快
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 10010;
int a, b, c, d, n, m, p;
ll ans = 0;
int mp[N][N], dis[N], vis[N];
inline int rd()
{
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;
}
void prim()
{
memset(vis, 0, sizeof(vis));
memset(dis, 0x3f, sizeof(dis));
dis[1] = 0;
for (int i = 1; i <= n + m; i++)
{
int t = -1;
for (int j = 1; j <= n + m; j++)
{
if (!vis[j] && (t == -1 || dis[j] < dis[t]))
{
t = j;
//cout << t<< endl;
}
}
//if (dis[t] == 0x3f)
{
// return;
}
vis[t] = 1;
ans += dis[t];
//cout << dis[t] << ' ' << t << endl;
//cout << ans << endl;
for (int j = 1; j <= m + n; j++)
{
dis[j] = min(dis[j], mp[t][j]);
}
}
}
int main()
{
n = rd(), m = rd(), a = rd(), b = rd(), c = rd(), d = rd(), p = rd();
int last = a;
memset(mp, 0x3f, sizeof(mp));//原来是这里忘了!!!!!!!!!
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
last = (1ll * (1ll * last * last * b % p + 1ll * last * c % p) % p + d) % p;
mp[i][j + n] = mp[j + n][i] = last;
//cout << last << ' ';
}
//cout << endl;
}
prim();
printf("%lld", ans);
return 0;
}
/*//啊,kruskal会超时。。。得用prim。。。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 5010;
int a, b, c, d, n, m, p;
ll ans = 0;
int f[N + N];
struct Nod
{
int u, v, w;
}nod[N*N];
inline int rd()
{
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;
}
bool cmp(Nod a, Nod b)
{
return a.w < b.w;
}
int Find(int x)
{
if (x == f[x])
{
return x;
}
return f[x] = Find(f[x]);
}
bool Judge(int a, int b)
{
int fa = Find(a);
int fb = Find(b);
if (fa != fb)
{
f[fa]=fb;
return false;
}
return true;
}
int main()
{
n = rd(), m = rd(), a = rd(), b = rd(), c = rd(), d = rd(), p = rd();
int last = a;
for (int i = 1; i <= n + m; i++)
{
f[i] = i;
}
int cnt = 1;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++,cnt++)
{
last = (1ll*(1ll*last * last * b % p + 1ll*last * c % p)%p + d) % p;
nod[cnt].u = i, nod[cnt].v = j+n, nod[cnt].w = last;
}
}
sort(nod+1, nod +cnt+1, cmp);
int p = 1;
for (int i = 1; i <=cnt; i++)
{
if (!Judge(nod[i].u, nod[i].v))
{
ans += nod[i].w;
p++;
if (p>= n + m)
{
break;
}
//cout << nod[i].w << endl;
//cout << nod[i].u << ' ' << nod[i].v << endl;
}
}
printf("%lld", ans);
return 0;
}*/