Connect the Cities Time limit:2000/1000 MS (java/others) Memory limit:32768/32768 K (java/others)
Total submission (s): 8540 Accepted Submission (s): 2397
Problem Description in 2100, since the sea level rise, most of the cities disappear. Though Some survived cities is still connected with others, but most of them become disconnected. The government wants to build some roads to connect all of these cities again, but they don't want to take too much.
Input The first line contains the number of test cases.
Each test case is starts with three integers:n, M and K. N (3 <= n <=500) stands for the number of survived cities, m (0 <= M <= 25000) stands for the number of roads you can choose to connect the cities and K (0 <= K <=) St ANDs for the number of still connected cities.
To make it easy, the cities is signed from 1 to N.
Then follow m lines, each contains three integers p, Q and C (0 <= C <=), means it takes C to connect P and Q.
Then follow k lines, each line starts with a integer t (2 <= t <= N) stands for the number of this connected cities . Then T integers follow stands for the ID of these cities.
Output for each case, output of the least money need to take, if it ' s impossible, just output-1.
Sample Input
1 6 4 3 1 4 2 2 6 1 2 3 5 3 4 33 2 1 2 2 1 3 3 4 5 6
Sample Output
1
Author Dandelion
Test instructions: A flood in a place that has caused some cities to be flooded and now wants to connect the remaining scattered cities through roads, and some of the cities are known to be connected now. can choose to repair the road has m, the city has a total of N, given the starting point of M road and road costs, ask at least how much money can be spent to ensure that all the city connectivity. The obvious Kruskal. Sort the edge right and then add the edge to the check set.
#include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <queue>
#include <climits> using namespace std;
const int MAX = 25003;
typedef struct road{int x;
int y;
int C;
}road;
Road Road[max];
int CR;
int pre[501];
void init (int n) {int i;
for (I=1;i<=n;++i) {pre[i] = i;
} CR = N-1;
} int root (int x) {if (x!=pre[x]) {pre[x] = root (Pre[x]);
} return pre[x];
} int merge (int x,int y) {if (x==-1) return 0;
int ret = 0;
int FX = root (x);
int fy = root (y);
if (fx!=fy) {--CR;
PRE[FX] = FY;
ret = 1;
} return ret;
} int cmp (const void *a,const void *b) {return (road *) a)->c-((road *) b)->c;}
int main () {//freopen ("In.txt", "R", stdin);
Freopen ("OUT.txt", "w", stdout);
int t,n,m,k,cid,tc,pre;
int sum,i,j;
scanf ("%d", &t);
while (t--) {scanf ("%d%d%d", &n,&m,&k);
Init (n);
for (i=0;i<m;++i) {scanf ("%d%d%d", &road[i].x,&road[i].y,&road[i].c); } sum= 0;
for (i=0;i<k;++i) {scanf ("%d", &TC);
Pre =-1;
for (j=0;j<tc;++j) {scanf ("%d", &cid);
Merge (PRE,CID);
Pre = CID;
}} qsort (Road,m,sizeof (road), CMP);
for (I=0;i<m;++i) {if (merge (ROAD[I].X,ROAD[I].Y) ==1) {sum + = road[i].c;
}} if (cr!=0) {printf (" -1\n");
}else{printf ("%d\n", sum);
}} return 0;
}