现在的位置: 首页 > 综合 > 正文

JOJ 1170 :Wire Is So Expensive 最小生成树

2013年07月16日 ⁄ 综合 ⁄ 共 1064字 ⁄ 字号 评论关闭

题目:http://acm.jlu.edu.cn/joj/showproblem.php?pid=1170

根据题目的输入特点,用kruskal算法最方便。

代码:

  1. #include <cstdio>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5. struct Edge {
  6.     int from, to, length;
  7.     Edge(int f, int t, int l):from(f),to(t),length(l){}
  8.     Edge() {}
  9.     Edge(const Edge& e) {
  10.     from = e.from;
  11.     to = e.to;
  12.     length = e.length;
  13.     }
  14.     bool operator<(const Edge& e) const {
  15.     return length < e.length;
  16.     }
  17. };
  18. int n;
  19. int main() {
  20.     freopen("in.txt""r", stdin);
  21.     int m;
  22.     int ans;
  23.     int id[32];
  24.     scanf("%d", &m);
  25.     while(m--) {
  26.     int a,b,c;
  27.     vector<Edge> ve;
  28.     scanf("%d", &n);
  29.     while(scanf("%d%d%d", &a, &b, &c), a||b||c) {
  30.         ve.push_back(Edge(a,b,c));
  31.     }
  32.     ans = 0;
  33.     for(int i = 0; i <= n; i++)
  34.         id[i] = i;
  35.     sort(ve.begin(), ve.end());
  36.     const int s = ve.size();
  37.     for(int i = 0;i < s; i++) {
  38.         int from = ve[i].from, to = ve[i].to;
  39.         if(id[from] != id[to]) {
  40.         replace(id, id+n+1, (int)id[to], (int)id[from]);
  41.         ans += ve[i].length;
  42.         }     
  43.     }
  44.     printf("%d/n", ans);
  45.     }
  46.     return 0;
  47. }

 

 

抱歉!评论已关闭.