思路:
只要连接到k个房间其中一个就可以,所以可以把k个房间并起来。
然后就是克鲁斯卡尔。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstdlib> 4 #include<cstring> 5 #include<string> 6 #include<queue> 7 #include<algorithm> 8 #include<map> 9 #include<iomanip> 10 #include<climits> 11 #include<string.h> 12 #include<cmath> 13 #include<stdlib.h> 14 #include<vector> 15 #define INF 1e7 16 #define MAXN 100010 17 #define maxn 1000010 18 #define Mod 1000007 19 #define N 1010 20 using namespace std; 21 typedef long long LL; 22 23 struct node{ 24 int a, b, c; 25 bool operator < (const node a) const{ 26 return c < a.c; 27 } 28 }s[N*500]; 29 30 int fa[N]; 31 int n, m, k; 32 33 int findset(int x) 34 { 35 if (fa[x] == x) return x; 36 return fa[x] = findset(fa[x]); 37 } 38 39 void merg(int a, int b) 40 { 41 int x = findset(a); 42 int y = findset(b); 43 if (x != y) { 44 fa[x] = y; 45 } 46 } 47 48 void init() 49 { 50 for (int i = 0; i <= n; ++i) 51 fa[i] = i; 52 } 53 54 int main() 55 { 56 while (cin >> n >> m >> k) { 57 init(); 58 int tmp, x; 59 cin >> tmp; 60 for (int i = 1; i < k; ++i) { 61 cin >> x; 62 fa[x] = tmp; 63 } 64 int a, b, c; 65 for (int i = 0; i < m; ++i) { 66 cin >> s[i].a >> s[i].b >> s[i].c; 67 } 68 sort(s,s+m); 69 int res = 0; 70 for (int i = 0; i < m; ++i) { 71 int x = findset(s[i].a); 72 int y = findset(s[i].b); 73 if (x != y) { 74 fa[x] = y; 75 res += s[i].c; 76 } 77 } 78 cout << res << endl; 79 } 80 return 0; 81 }