Introduction

This is my blog of programming, I take notes and leave codes of computer science problems I solved here. Be my guest to comment :)

Sunday, December 9, 2012

uva 11631 - Dark roads


/*
Problem link
Type: Graph
Algorithm: Kruskal, minimum spanning tree, using priority queue
*/
#include <iostream>
#include <queue>
#include <vector>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <fstream>
using namespace std;
const int maxn = 200010;
//---------------------------------
class Edge {
public:
 int a;
 int b; 
 int t;
 
 Edge() {}
 Edge(const int aa, const int bb, const int tt) {
  a = aa;
  b = bb;
  t = tt;
 } 
 
 Edge(const Edge& e) {
  a = e.a;
  b = e.b;
  t = e.t;
 }
 
 bool operator<(const Edge& e)const { return (t<e.t); }
 bool operator>(const Edge& e)const { return (t>e.t); }
};
//---------------------------------
bool readfile();
bool ok(Edge e);
//---------------------------------
priority_queue<Edge, vector<Edge>, greater<Edge> > c;
int n,m,sum;
int fa[maxn];
//---------------------------------
int main() {
 while (readfile()) 
 {
  int result = 0;
  int cnt = 0;
  for (int i=1; i<=n; i++) fa[i] = i;
  for (int i=1; i<=m; i++)
  {
   Edge e = c.top();
   c.pop();
   if (ok(e)) 
   {
    result += e.t;
    cnt++;
   }
   if (cnt==n-1) break;
  }
  result = sum - result;
  cout << result << endl;
  while (!c.empty()) c.pop();
 }
 return 0;
}
//---------------------------------
bool readfile() {
 cin >> n >> m;
 sum = 0;
 if (n==0 && m==0) return(false);
 for (int i=1; i<=m; i++) 
 {
  int u,v,t;
  cin >> u >> v >> t;
  sum+=t;
  c.push(Edge(u,v,t));
 }
 return(true);
}
//---------------------------------
bool ok(Edge e) {
 int a = e.a, b = e.b;
 while (a!=fa[a]) a = fa[a];
 while (b!=fa[b]) b = fa[b];
 if (a==b) return(false);
 else
 {
  if (a<b) fa[b] = a;
  else fa[a] = b;
  return(true);
 }
}
//---------------------------------

No comments:

Post a Comment