原题:https://www.luogu.com.cn/problem/P1682
思路:用一个二维数组记录男女有没有吵嘴,然后两个女生联合的时候,顺便把吵嘴关系也转移,最后遍历一次吵嘴关系,记录最小值,最小值+k就是答案,注意答案上限是n。
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
using namespace std;
int n, m, k, f;
const int maxn = 255;
int father[maxn];
int relation[maxn][maxn];
int minv = 9999999;
void init()
{
for (int i = 0; i <= n; i++)
father[i] = -1;
}
int find(int number)
{
if (father[number] == -1)
return number;
else
{
father[number] = find(father[number]);
return father[number];
}
}
int uni(int p1, int p2)
{
int f1 = find(p1);
int f2 = find(p2);
if (f1 == f2)
return 0;
else
{
father[f1] = f2;
for (int i = 1; i <= n; i++)//转移吵嘴关系
{
if (relation[p1][i] || relation[p2][i])//只要有一方是不吵嘴,另一方也要是不吵嘴
{
relation[p1][i] = 1;
relation[p2][i] = 1;
}
}
return 1;
}
}
int coculate()
{
for (int i = 1; i <= n; i++)
{
int total = 0;
for (int j = 1; j <= n; j++)
{
if (relation[i][j] == 1)
total++;
}
minv = min(total, minv);
}
return minv;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m >> k >> f;
init();
while (m--)
{
int num1, num2;
cin >> num1 >> num2;
relation[num1][num2] = 1;
}
while (f--)
{
int num1, num2;
cin >> num1 >> num2;
uni(num1, num2);
}
coculate();
if (minv + k <= n)
{
cout << minv + k << endl;
}
else
{
cout << n << endl;
}
}