题意
有 n n n个菜和 k k k个人,每个人都有喜欢的两种菜,他会吃掉自己喜欢的菜,如果没有他喜欢吃的菜,他就会沮丧,让你安排一种吃菜顺序,让沮丧的人变少。
解题方法
先连边,我们发现不连通的没有影响,我们考虑连通块大小大于 1 1 1 的,如果这里里面包含 n n n 盘菜,我们可以发现我们可以通过安排顺序能让 n − 1 n-1 n−1个人满足,因为除了第一个人吃两盘其他的都吃一盘,然后用并查集维护一下,最后统计一下答案。
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int fa[200100];
int find(int x)
{
if(x==fa[x])return x;
else return fa[x]=find(fa[x]);
}
int main()
{
int n,k;
int tot=0;
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++)
fa[i]=i;
for(int i=1;i<=k;i++)
{
int x,y;
scanf("%d%d",&x,&y);
x=find(x);
y=find(y);
if(x!=y)
{
tot++;
fa[y]=x;
}
}
cout<<k-tot<<'\n';
return 0;
}