2014-09-09 16:39:37
思路:做完这题,对最小生成树的理解也就差不多了。直接暴力可搞,但可以优化。先对原图进行一次Kruskal,求出最优n-1条边,然后用二进制枚举方法(循环 or DFS),考虑每个套餐的包含点(m个),买这个套餐相当于加进来m-1条权为0的边,然后再用一次Kruskal,先考虑m-1条0权边再考虑第一次kru出来的n-1条边即可。
(被这输出坑了两发 QAQ)
1 /************************************************************************* 2 > File Name: Uva1151.cpp 3 > Author: Nature 4 > Mail: 564374850@qq.com 5 > Created Time: Tue 09 Sep 2014 02:27:23 PM CST 6 ************************************************************************/ 7 8 #include <cstdio> 9 #include <cstring> 10 #include <cstdlib> 11 #include <cmath> 12 #include <vector> 13 #include <queue> 14 #include <iostream> 15 #include <algorithm> 16 using namespace std; 17 typedef long long ll; 18 const int INF = 0x3f3f3f3f; 19 20 struct edge{ 21 int u,v; 22 double dis; 23 }e[1000005]; 24 25 edge te[10005]; 26 27 struct pac{ 28 int n,f; 29 int v[1005]; 30 }p[10]; 31 32 int T,n,s,x[1005],y[1005],cnt; 33 int fa[1005],ncnt,tcnt,ans; 34 35 int Dis(int a,int b){ 36 return (x[b]-x[a])*(x[b]-x[a]) + (y[b]-y[a])*(y[b]-y[a]); 37 } 38 39 int Find(int x){ return fa[x] == x ? x : fa[x] = Find(fa[x]);} 40 41 void Kruskal(){ 42 for(int i = 1; i <= n; ++i) fa[i] = i; 43 ncnt = 0; 44 for(int i = 1; i <= cnt; ++i){ 45 int x = Find(e[i].u); 46 int y = Find(e[i].v); 47 if(x != y){ 48 fa[y] = x; 49 e[++ncnt] = e[i]; 50 } 51 } 52 } 53 54 bool cmp(edge a,edge b){ 55 return a.dis < b.dis; 56 } 57 58 void Cal(int st){ 59 int x,y,fee = 0; 60 tcnt = 0; 61 for(int i = 1; i <= s; ++i){ 62 if(st & (1 << i)){ 63 for(int j = 1; j < p[i].n; ++j){ 64 te[++tcnt].u = p[i].v[j]; 65 te[tcnt].v = p[i].v[j + 1]; 66 te[tcnt].dis = 0; 67 } 68 fee += p[i].f; 69 } 70 } 71 for(int i = 1; i <= n; ++i) fa[i] = i; 72 for(int i = 1; i <= tcnt; ++i){ 73 x = Find(te[i].u); 74 y = Find(te[i].v); 75 if(x != y) fa[y] = x; 76 } 77 for(int i = 1; i <= ncnt; ++i){ 78 x = Find(e[i].u); 79 y = Find(e[i].v); 80 if(x != y){ 81 fa[y] = x; 82 fee += e[i].dis; 83 } 84 } 85 if(fee < ans){ 86 ans = fee; 87 } 88 } 89 90 void Dfs(int p,int st){ 91 if(p > s){ 92 Cal(st); 93 return; 94 } 95 Dfs(p + 1,st | (1 << p)); 96 Dfs(p + 1,st); 97 } 98 99 int main(){ 100 scanf("%d",&T); 101 while(T--){ 102 scanf("%d%d",&n,&s); 103 for(int i = 1; i <= s; ++i){ 104 scanf("%d%d",&p[i].n,&p[i].f); 105 for(int j = 1; j <= p[i].n; ++j) 106 scanf("%d",&p[i].v[j]); 107 } 108 for(int i = 1; i <= n; ++i) 109 scanf("%d%d",x + i,y + i); 110 cnt = 0; 111 for(int i = 1; i <= n; ++i) 112 for(int j = i + 1; j <= n; ++j){ 113 if(i == j) continue; 114 e[++cnt].u = i; 115 e[cnt].v = j; 116 e[cnt].dis = Dis(i,j); 117 } 118 sort(e + 1,e + cnt + 1,cmp); 119 Kruskal(); 120 ans = INF; 121 Dfs(1,0); 122 printf("%d\n",ans); 123 if(T) printf("\n"); 124 } 125 return 0; 126 }