# 小米2013校招笔试算法题-朋友圈个数

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10000
char map[N][N];
char used[N];
void dfs(int i, int n)
{
int j;
used[i] = 1;
for(j = 1; j <= n; j++) {
if (map[i][j] && !used[j])
dfs(j, n);
}
}
/* 判断是否存在未访问节点
* 若存在，则返回第一个未访问节点编号
* 若不存在，则返回-1
*/
int isVisitedAll(int n)
{
int i;
for (i = 1; i <= n; i++)
if (used[i] == 0)
return i;
return -1;
}
int main(int argc, char **argv)
{
int n, m;
int a, b, i, sum, cur;
while (scanf("%d%d", &n, &m) != EOF) {
if (n == 0)
break;
memset(map, 0, sizeof(map));
memset(used, 0, sizeof(used));
sum = 0;
for (i = 0; i < m; i++) {
scanf("%d%d", &a, &b);
map[a][b] = map[b][a] = 1;
}
while((cur = isVisitedAll(n)) != -1) {
sum++;
dfs(cur, n);
}
printf("%d\n", sum);
}
return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100000
int father[N];
void init(int n)
{
int i;
for (i = 1; i <= n; i++)
father[i] = i;
}
int getFather(int v)
{
if (father[v] == v)
return v;
else {

father[v] = getFather(father[v]);
return father[v];
}
}
void merge(int x, int y)
{
int fx = getFather(x);
int fy = getFather(y);
if (fx < fy)
father[fx] = fy;
else
father[fy] = fx;
}
int same(int x, int y)
{
return getFather(x) == getFather(y);
}
int main(int argc, char **argv)
{
int n, m;
int a, b;
int i;
int sum;
while (scanf("%d%d", &n, &m) != EOF) {

if (n == 0)
break;
init(n);
sum = 0;
for (i = 1; i <= m; i++) {
scanf("%d%d", &a, &b);
merge(a, b);
}
for (i = 1; i <= n; i++) {
if (getFather(i) == i)
sum++;
}
printf("%d\n", sum);
}
return 0;
}


posted @ 2016-03-24 09:39  int32bit  阅读(732)  评论(0编辑  收藏