Description
Berland has n cities connected by m bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed that you can get from any city to any other one, using only the existing roads.
The President of Berland decided to make changes to the road system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another).
In order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered separate, if no road leads into it, while it is allowed to have roads leading from this city.
Help the Ministry of Transport to find the minimum possible number of separate cities after the reform.
Input
The first line of the input contains two positive integers, n and m — the number of the cities and the number of roads in Berland (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000).
Next m lines contain the descriptions of the roads: the i-th road is determined by two distinct integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the numbers of the cities connected by the i-th road.
It is guaranteed that there is no more than one road between each pair of cities, but it is not guaranteed that from any city you can get to any other one, using only roads.
Output
Print a single integer — the minimum number of separated cities after the reform.
Sample Input
Input
4 32 11 34 3
Output
1
Input
5 52 11 32 32 54 3
Output
0
Input
6 51 22 34 54 65 6
Output
1
Hint
In the first sample the following road orientation is allowed: , , .
The second sample: , , , , .
The third sample: , , , , .
//这是一道并查集判环问题,之前做过这种类似的,但是忘了,一会巩固一下;
/*总结 *****并查集判环*****
并查集是一种树型的数据结构,用于处理一些不相交集合(Disjoint Sets)的合并及查询问题。常常在使用中以森林来表示。
如何用并查集来判断一个图是否有环?
此时的1同时是 2 3 的上级,如果接下来mix (2,3)
必然会连成一个环
在程序中为 if(fx==fy) a[fx]=a[fy]=a[x]=a[y]=true;//即确定1 2 3 是环的一部分
接下来mix(3,4),如果3 的环一部分,(或者是4、_find(3),_find(4))必可以每个元素都可以单向指向
如果这样。。。4 ,5 就没法都做到单向指向。。
即想每个元素都可以单向指向一定要有环。。。
******o(^▽^)o******
*/
#include <iostream> #include <algorithm> #include <cstring> using namespace std; int pre[100005]; bool a[100005]; int _find(int x) { int r=pre[x]; while(r!=pre[r]) r=pre[r]; int i=x,j; while(pre[i]!=r) { j=pre[i]; pre[i]=r; i=j; } return r; } void mix(int x,int y) { int fx=_find(x),fy=_find(y); if(fx!=fy) { pre[fx]=fy; if(a[fx]||a[fy]||a[x]||a[y]) a[fx]=a[fy]=a[x]=a[y]=true; } else a[fx]=a[fy]=a[x]=a[y]=true; } int main() { int n,m,ans; while(cin>>n>>m) { ans=0; for(int i=1;i<=n;i++) pre[i]=i; memset(a,false,sizeof(a)); for(int i=1;i<=m;i++) { int a,b; cin>>a>>b; mix(a,b); } for(int i=1;i<=n;i++) { if(a[_find(i)]==false&&_find(i)==i) ans++; } cout<<ans<<endl; } return 0; }