HDU 1863 畅通工程
http://acm.hdu.edu.cn/showproblem.php?pid=2544
简单题,开始学图论了。
//Danceonly #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <algorithm> using namespace std; typedef long long LL; const int INF = 100000007; const int maxn = 100050; const double Pi = atan(1) * 4; #define MIN(a,b) (a > b ? b : a) #define MAX(a,b) (a > b ? a : b) int N,M; int p[10005]; int c[10005],w[10005],v[10005],u[10005]; int cmp(int i,int j) { return w[i] < w[j] ; } int Find(int x) { return x == p[x] ? x : p[x] = Find(p[x]); } int tt[10005]; int main() { while (scanf("%d%d",&N,&M) == 2 && N) { int aa[101]; memset(aa,0,sizeof(aa)); for (int i=0;i<N;i++) { scanf("%d%d%d",&u[i],&v[i],&w[i]); aa[u[i]] = 1; aa[v[i]] = 1; } for (int i=0;i<N;i++) c[i] = i; sort(c,c+N,cmp); for (int i=1;i<=M;i++) tt[i] = 1; for (int i=1;i<=M;i++)p[i] = i; int ans = 0; int max_n = 0; for (int i=0;i<N;i++) { int e = c[i]; int x = Find(u[e]); int y = Find(v[e]); if (x != y) { ans += w[e]; p[x] = y; int temp = tt[x] + tt[y]; tt[p[x]] = temp; if (max_n < temp)max_n = temp ; } } if (max_n == M)printf("%d\n",ans); else printf("?\n"); } return 0; }