University of Ulm Local Contest
Problem D: Dark roads
What is the maximum daily amount of money the government of Byteland can save, without making their inhabitants feel unsafe?
Input Specification
The input file contains several test cases. Each test case starts with two numbers m and n, the number of junctions in Byteland and the number of roads in Byteland, respectively. Input is terminated by m=n=0. Otherwise, 1 ≤ m ≤ 200000and m-1 ≤ n ≤ 200000. Then follow n integer triples x, y, z specifying that there will be a bidirectional road between x andy with length z meters (0 ≤ x, y < m and x ≠ y). The graph specified by each test case is connected. The total length of all roads in each test case is less than 231.Output Specification
For each test case print one line containing the maximum daily amount the government can save.Sample Input
7 11 0 1 7 0 3 5 1 2 8 1 3 9 1 4 7 2 4 5 3 4 15 3 5 6 4 5 8 4 6 9 5 6 11 0 0
Sample Output
51
minimum spanning tree - kruskal
#include<stdio.h>
#include<cstring>
#include<queue>
#define REP(i, b, n) for (int i = b; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define DBG 0
#define MAXM 200000
using namespace std;
int N,M,D,e;
int v1[MAXM],v2[MAXM],w[MAXM],p[MAXM];
struct Node{
Node(int a,int b,int c):v1(a),v2(b),dis(c){}
bool operator <(const Node b)const {return dis>b.dis;}
int v1,v2,dis;
};
void addedge(int a,int b,int c){
v1[e]=a,v2[e]=b,w[e]=c,e++;
}
int find(int v){
if(p[v]==v)return v;
return p[v]=find(p[v]);
}
void unit(int from,int to){
p[find(from)]=p[find(to)];
}
void ans(){
int a,b,c,d=0,sum=0;
priority_queue<Node>q;
rep(i,e)q.push(Node(v1[i],v2[i],w[i]));
rep(i,N)p[i]=i;
while(d<N-1){
a=q.top().v1,b=q.top().v2,c=q.top().dis,q.pop();
if(DBG)printf("a b %d %d\n",a,b);
if(find(a)!=find(b))unit(a,b),sum+=c,d++;
}
printf("%d\n",D-sum);
}
int main(){
int a,b,c;
while(scanf("%d%d",&N,&M)==2){
D=0,e=0;
if(N==0&&M==0)break;
rep(i,M)scanf("%d%d%d",&a,&b,&c),addedge(a,b,c),D+=c;
ans();
}
return 0;
}
沒有留言:
張貼留言