//碰巧搜到-_-
#include <bits/stdc++.h>
using namespace std;
bool Graph[100][100];
bool vis[100];
void DFS(int s);
int n, m;
int num;
int main()
{
while(cin >> n >> m)
{
num = 0;
memset(vis, 0, sizeof(vis));
memset(Graph, 0, sizeof(Graph));
for(int i = 1; i <= m; i++)
{
int u, v;
cin >> u >> v;
Graph[u][v] = Graph[v][u] = 1;
}
vis[1] = 1;
++num;
DFS(1);
cout << n-num+1 << endl;
}
return 0;
}
void DFS(int s)
{
for(int i = 1; i <= n; i++)
{
if(!vis[i] && Graph[s][i])
{
num ++;
vis[i] = 1;
DFS(i);
}
}
}
#include <bits/stdc++.h>
using namespace std;
int pre[1010];
int Find(int x);
int join(int x, int y);
int main()
{
int n, m;
while(cin >> n >> m)
{
for(int i = 1; i <= n; i++)
{
pre[i] = i;
}
for(int i = 1; i <= m; i++)
{
int x, y;
cin >> x >> y;
join(x, y);
}
int num = 0;
for(int i = 1; i <= n; i++)
{
if(pre[i] == i)
{
++num;
}
}
cout << num << endl;
}
return 0;
}
int Find(int x)
{
int r = x;
while(pre[r] != r)
r = pre[r];
int i = x, j;
while(i != r)
{
j = pre[i];
pre[i] = r;
i = j;
}
return r;
}
int join(int x, int y)
{
int fx = Find(x), fy = Find(y);
if(fx != fy)
{
pre[fx] = fy;
}
}
SDUT 2129 树结构练习——判断给定森林中有多少棵树
最新推荐文章于 2017-07-14 09:13:40 发布