市政府“惠民工程”的目标是在全市n个居民点间之架设煤气管道(但不一定有直接的管道相连,只要能间接通过管道可达即可)。很显然最多可架设 n(n-1)/2条管道,然而实际上要连通n个居民点只需架设n-1条管道就可以了。现请你编写程序,计算出该惠民工程需要的最低成本。
测试输入包含若干测试用例。每个测试用例的第1行给出居民点数目M ( < =100 )、 评估的管道条数 N;随后的 N 行对应居民点间管道的成本,每行给出一对正整数,分别是两个居民点的编号,以及此两居民点间管道的成本(也是正整数)。为简单起见,居民点从1到M编号。
对每个测试用例,在1行里输出全市管道畅通所需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
3 3
1 2 1
1 3 2
2 3 4
3 1
2 3 2
3
?
#include <vector>
#include <iostream>
#include <string>
#include <map>
#include <stack>
#include <cstring>
#include <queue>
#include <list>
#include <cstdio>
#include <set>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include <cctype>
#include <sstream>
#include <functional>
using namespace std;
#define LL long long
#define INF 1E4 * 1E9
#define pi acos(-1)
#define endl '\n'
#define me(x) memset(x,0,sizeof(x));
const int maxn=1e4+5;
const int maxx=1e7+5;
//
//找一次树高会减少
struct node
{
int u,v,c;
}q[maxn];
int n,m;
bool cmp(node a,node b)
{
return a.c<b.c;
}
int fa[maxn];
int fi(int x)
{
return fa[x]==x?x:fi(fa[x]);
}
int check(int x,int y)
{
int p1=fi(x),p2=fi(y);
if(x==y) return 1;
else return 0;
}
int main()
{
while(cin>>n>>m)
{
for(int i=1;i<=m;i++)
cin>>q[i].u>>q[i].v>>q[i].c;
sort(q+1,q+m+1,cmp);
for(int i=1;i<=n;i++)
fa[i]=i;
int cur=1,cos=0;
for(int i=1;i<=m;i++)
{
int fx=fi(q[i].u),fy=fi(q[i].v);
if(fx!=fy)
{
fa[fx]=fy;
cur++;
cos+=q[i].c;
}
}
if(cur==n) cout<<cos<<endl;
else cout<<"?"<<endl;
}
}