浙江大学OJ果然难一些,数据更加严格啊!在杭电上写的一些AC的程序在这里就是WA,以后编程一定要多注意细节,细节决定成败。加油!!!
In last winter, there was a big snow storm in South China. The electric system was damaged seriously. Lots of power lines were broken and lots of villages lost contact with the main power grid. The government wants to reconstruct the electric system as soon as possible. So, as a professional programmer, you are asked to write a program to calculate the minimum cost to reconstruct the power lines to make sure there's at least one way between every two villages.
Input
Standard input will contain multiple test cases. The first line of the input is a single integerT (1 <=T <= 50) which is the number of test cases. And it will be followed byT consecutive test cases.
In each test case, the first line contains two positive integers N andE (2 <=N <= 500, N <= E <= N * (N - 1) / 2), representing the number of the villages and the number of the original power lines between villages. There followE lines, and each of them contains three integers,A, B,K (0 <= A, B < N, 0 <=K < 1000). A and B respectively means the index of the starting village and ending village of the power line. IfK is 0, it means this line still works fine after the snow storm. IfK is a positive integer, it means this line will cost K to reconstruct. There will be at most one line between any two villages, and there will not be any line from one village to itself.
Output
For each test case in the input, there's only one line that contains the minimum cost to recover the electric system to make sure that there's at least one way between every two villages.
Sample Input
1 3 3 0 1 5 0 2 0 1 2 9
Sample Output
5
#include <iostream> #include <cstdio> #include <cstring> const int INF=1000000000; const int maxn=510; using namespace std; int map[maxn][maxn],dis[maxn],visited[maxn]; int main() { int n,a,b,k,i,j,N,E,mindistance,min,t; scanf("%d",&n); while (n--) { memset(visited,0,sizeof(visited)); mindistance=0; scanf("%d%d",&N,&E); for (i=0;i<N;i++) { for (j=0;j<N;j++) { map[i][j]=INF; } } for (i=0;i<E;i++) { scanf("%d%d%d",&a,&b,&k); map[a][b]=map[b][a]=k; } for (j=0;j<N;j++) { dis[j]=map[0][j]; } visited[0]=1; for (i=0;i<N;i++) { min=INF; for (j=0;j<N;j++) { if(!visited[j] && min>dis[j]) { min=dis[j]; t=j; } } if(min!=INF)//值得注意的地方 mindistance+=min; visited[t]=1; for (j=0;j<N;j++) { if (!visited[j] && dis[j]>map[t][j]) { dis[j]=map[t][j]; } } } printf("%d\n",mindistance); } return 0; }