4001
Problem A
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 82 Accepted Submission(s) : 34
3 0 990 692 990 0 179 692 179 0 1 1 2
179
给出总共的村庄的编号,然后在下面的N行N列中,列举出从i节点到j节点所有的权值,都为最后输入的那个数,之后输入q组表示有q组数据,表示着K组已经连通,求出使所有的村庄相连的路径的最小的权值;
思路:
可以用 贪心算法+并查集
也可以用最小生成树的两种算法;
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <ctime>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#define oo 0x13131313
using namespace std;
int N,M;
int Set[1001];
int ans;
void YCL()
{
ans=0;
for(int i=0;i<=N;i++)
Set[i]=i;
}
int find(int x)
{
if(x!=Set[x])
Set[x]=find(Set[x]);
return Set[x];
}
int Union(int a,int b)
{
int a1=find(a);
int b1=find(b);
if(a1!=b1)
{
Set[a1]=b1;
return 1;
}
else return 0;
}
void input()
{
cin>>N>>M;
int a,b;
YCL();
for(int i=1;i<=M;i++)
{
cin>>a>>b;
if(Union(a,b))
ans++;
}
int main()
{
int T;
cin>>T;
while(T--)
{
input();
cout<<N-ans<<endl;
}
return 0;
}