算法思路:并查集。
其实这一题没有用到最小生成树,因为求连通分支的个数只要用到并查集,而最终的结果就是:count - 1。
当然老规矩count为0的时候需要单独讨论。
//模板开始
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <fstream>
#include <map>
#include <set>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include<iomanip>
#include<string.h>
#define SZ(x) (int(x.size()))
using namespace std;
int toInt(string s){
istringstream sin(s);
int t;
sin>>t;
return t;
}
template<class T> string toString(T x){
ostringstream sout;
sout<<x;
return sout.str();
}
typedef long long int64;
int64 toInt64(string s){
istringstream sin(s);
int64 t;
sin>>t;
return t;
}
template<class T> T gcd(T a, T b){
if(a<0)
return gcd(-a, b);
if(b<0)
return gcd(a, -b);
return (b == 0)? a : gcd(b, a % b);
}
//模板结束(通用部分)
#define ifs cin
int findset(int x, int pa[]) //递归版findset
{
return pa[x] != x ? pa[x] = findset(pa[x], pa) : x;
}
#define MAX_SIZE 1005
int next_node[MAX_SIZE]; //存储有向图的边
int flag[MAX_SIZE]; //标记节点是否存在
//int in[MAX_SIZE]; //存储节点的入度
//int out[MAX_SIZE]; //存储节点的出度
void init() //初始化
{
for(int i = 0; i < MAX_SIZE; i++)
{
next_node[i] = i;
}
//memset(in, 0, sizeof(in));
//memset(out, 0, sizeof(out));
memset(flag, 0, sizeof(flag));
}
int findset(int a) //找元素所在集合的代表元(因为用了路径压缩,路径压缩的主要目的是为了尽快的确定元素所在的集合)
{
int v = a;
while(next_node[a] != a)
{
a = next_node[a];
}
while(v != next_node[v])
{
int temp = next_node[v];
next_node[v] = a;
v = temp;
}
return a;
}
void union_nodes(int a, int b) //集合合并
{
int a1 = findset(a);
int b1 = findset(b);
next_node[a1] = b1;
}
//【图论06】最小生成树 1002 畅通工程
int main()
{
//ifstream ifs("shuju.txt", ios::in);
int m, n;
int a, b;
while(scanf("%d", &m) && m != 0)
{
scanf("%d", &n);
//cin>>n;
init();
for(int i = 1; i <= m; i++)
{
flag[i] = 1;
}
for(int i = 0; i < n; i++)
{
scanf("%d%d", &a, &b);
//cin>>a>>b;
union_nodes(a, b);
}
int count = 0;
for(int j = 0; j <= m; j++) //计算有向图中连通分支的个数
{
if(next_node[j] == j && flag[j] != 0)
{
count++;
}
}
count -= 1;
if(count >= 0)
{
printf("%d\n", count);
}
else
{
printf("0\n");
}
}
return 0;
}