Description
Input
注意:两个城市之间可以有多条道路相通,也就是说
3 3
1 2
1 2
2 1
这种输入也是合法的
当N为0时,输入结束,该用例不被处理。
Output
Sample Input
4 2
1 3
4 3
3 3
1 2
1 3
2 3
5 2
1 2
3 5
999 0
0
Sample Output
1
0
2
998
Hint
Hint Huge input, scanf is recommended.
其实就是判断树和孤立点的数量
#include<iostream>
#include<vector>
#include<stack>
#include<list>
using namespace std;
int main()
{
int n,m;
while(cin>>n>>m&&n){
vector<list <int > > adj;
int i;
stack<int >st;
vector<bool>visited;
visited.resize(n+1);
for(i=1;i<n+1;i++)
visited[i]=false;
adj.resize(n+1);
for(i=0;i<m;i++){
int a,b;
cin>>a>>b;
adj[a].push_back(b);
adj[b].push_back(a);
}
int forest=0;
for(i=1;i<n+1;i++){
if(visited[i]==false){
if(adj[i].empty())
forest++;
else{
st.push(i);
while(!st.empty()){
int top=st.top();
visited[top]=true;
st.pop();
list<int >::iterator p=adj[top].begin();
while(p!=adj[top].end()){
if(visited[*p]==false){
visited[*p]=true;
int newtop=*p;
st.push(newtop);
}
p++;
}
}
forest++;
}
}
}
cout<<forest-1<<endl;
}
return 0;
}