There are N villages, which are numbered from 1 to N, and you should build some roads such that every two villages can connect to each other. We say two village A and B are connected, if and only if there is a road between A and B, or there exists a village C such that there is a road between A and C, and C and B are connected.
We know that there are already some roads between some villages and your job is the build some roads such that all the villages are connect and the length of all the roads built is minimum.
We know that there are already some roads between some villages and your job is the build some roads such that all the villages are connect and the length of all the roads built is minimum.
The first line is an integer N (3 <= N <= 100), which is the number of villages. Then come N lines, the i-th of which contains N integers, and the j-th of these N integers is the distance (the distance should be an integer within [1, 1000]) between village i and village j.
Then there is an integer Q (0 <= Q <= N * (N + 1) / 2). Then come Q lines, each line contains two integers a and b (1 <= a < b <= N), which means the road between village a and village b has been built.
Then there is an integer Q (0 <= Q <= N * (N + 1) / 2). Then come Q lines, each line contains two integers a and b (1 <= a < b <= N), which means the road between village a and village b has been built.
You should output a line contains an integer, which is the length of all the roads to be built such that all the villages are connected, and this value is minimum.
3 0 990 692 990 0 179 692 179 0 1 1 2
179
一看就知道是最小生成树,心太急了,把100看成数组长度,上去两发RE,浇了一头冷水,发现后,直接秒了。
#include <map> #include <set> #include <cmath> #include <queue> #include <string> #include <vector> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define inf 0x3f3f3f3f #define eps 1e-10 #define maxn 300005 #define zero(a) fabs(a)<eps #define Min(a,b) ((a)<(b)?(a):(b)) #define Max(a,b) ((a)>(b)?(a):(b)) #define pb(a) push_back(a) #define mem(a,b) memset(a,b,sizeof(a)) #define LL long long #define lson step<<1 #define rson step<<1|1 #define MOD 1000000009 #define sqr(a) ((a)*(a)) using namespace std; int Count; int f[10005]; int getf(int v) { if(v != f[v]) { f[v] = getf(f[v]); return f[v]; } } int merge(int v, int u) { int t1 = getf(v); int t2 = getf(u); if(t1 != t2) { f[t1] = t2; return 1; } return 0; } struct edge{ int v,u; int w; }e[10005]; bool cmp(edge x, edge y) { return x.w < y.w; } int main() { int N, W, Q; int a, b; Count = 0; scanf("%d",&N); int t = 0; for(int i = 1; i <= N; i++) { for(int j = 1; j <= N; j++) { scanf("%d",&W); if(i != j) { e[t].v = i; e[t].u = j; e[t].w = W; t++; } } } for(int i = 1; i <= N; i++) f[i] = i; int sum = 0; scanf("%d",&Q); while(Q--) { scanf("%d%d",&a, &b); if(merge(a , b)) { Count++; } } sort(e, e+t, cmp); for(int i = 0; i < t; i++) { if(merge(e[i].v,e[i].u)) { Count++; sum += e[i].w; } if(Count == N-1) break; } printf("%d\n",sum); return 0; }