畅通工程:
这道题主要是考察并查集的知识
程序如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int pre[1010];
int zhao(int root)//查找根结点
{
int son, tmp;
son = root;
while(root != pre[root])
root = pre[root];
while(son != root) //路径压缩,将此路径中的每一个元素的直系上司都变为最高的root
{
tmp = pre[son];
pre[son] = root;
son = tmp;
}
return root;
}
int main()
{
int num, road, total, i, start, end1, root1, root2;
while(scanf("%d%d", &num, &road) && num)
{
total = num - 1; //最少可以的路数
for(i = 1; i <= num; ++i)
pre[i] = i;
while(road--)
{
scanf("%d%d", &start, &end1);
root1 = zhao(start);
root2 = zhao(end1);
if(root1 != root2)
{
pre[root1] = root2;
total--;(要建的路)就少一个
}
}
printf("%d\n", total);
}
return 0;
}