D. Cow and Snacks
The legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo!
There are n snacks flavors, numbered with integers 1,2,…,n. Bessie has n snacks, one snack of each flavor. Every guest has exactly two favorite flavors. The procedure for eating snacks will go as follows:
First, Bessie will line up the guests in some way.
Then in this order, guests will approach the snacks one by one.
Each guest in their turn will eat all remaining snacks of their favorite flavor. In case no favorite flavors are present when a guest goes up, they become very sad.
Help Bessie to minimize the number of sad guests by lining the guests in an optimal way.
Input
The first line contains integers n and k (2≤n≤105, 1≤k≤105), the number of snacks and the number of guests.
The i-th of the following k lines contains two integers xi and yi (1≤xi,yi≤n, xi≠yi), favorite snack flavors of the i-th guest.
Output
Output one integer, the smallest possible number of sad guests.
Examples
input
5 4
1 2
4 3
1 4
3 4
output
1
input
6 5
2 3
2 1
3 4
6 5
4 5
output
0
Note
In the first example, Bessie can order the guests like this: 3,1,2,4. Guest 3 goes first and eats snacks 1 and 4. Then the guest 1 goes and eats the snack 2 only, because the snack 1 has already been eaten. Similarly, the guest 2 goes up and eats the snack 3 only. All the snacks are gone, so the guest 4 will be sad.
In the second example, one optimal ordering is 2,1,3,5,4. All the guests will be satisfied.
解题思路:
N种饼,一堆人按顺序吃饼,每个人只有两种饼可以吃,问怎么安排顺序让一个饼都吃不到的人数最少。用并查集表示每个人吃的饼的集合,如果两个饼在同一个集合中,说明两个饼都被吃完了,如果两个饼不在同一个集合中,说明至少还有一个饼可以吃,那么把他们吃掉,同时两个集合合并为一个。那么统计吃不到饼的人数就很简单了。
AC代码:
#include <iostream>
using namespace std;
int mark[100050];
int par[100050];
int find(int root) // 带路径压缩查找
{
return par[root] == root ? root : par[root] = find(par[root]);
}
int main()
{
for(int i = 0 ; i < 100050 ; i ++)
par[i] = i;
int n,k;
int a,b;
cin>>n>>k;
int ans = 0;
for(int i = 1 ; i <= k ; i ++)
{
cin>>a>>b;
if((a=find(a)) == (b=find(b))) // 统计人数
ans ++;
else // 合并集合
par[b] = a;
}
cout<<ans<<endl;
return 0;
}