标签:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4786
先跑一遍最小生成树,注意判断是否已全部联通(用一个记号来统计最后生成树中有多少条边)。再记下最小生成树的权值和A。
再反向排序,求一遍最大生成树。记下权值和B。问题转换成求[A,B]内是否有斐波那契数存在。
1 #include <algorithm> 2 #include <iostream> 3 #include <iomanip> 4 #include <cstring> 5 #include <climits> 6 #include <complex> 7 #include <fstream> 8 #include <cassert> 9 #include <cstdio> 10 #include <bitset> 11 #include <vector> 12 #include <deque> 13 #include <queue> 14 #include <stack> 15 #include <ctime> 16 #include <set> 17 #include <map> 18 #include <cmath> 19 20 using namespace std; 21 22 typedef struct P { 23 int u; 24 int v; 25 int w; 26 }P; 27 28 bool cmp1(P p1, P p2) {return p1.w < p2.w;} 29 bool cmp2(P p1, P p2) {return p1.w > p2.w;} 30 int A, B; 31 32 const int maxn = 100010; 33 int n, m, cnt; 34 int pre[maxn]; 35 int fib[maxn]; 36 P e[maxn]; 37 38 int find(int x) { 39 return x == pre[x] ? pre[x] : pre[x] = find(pre[x]); 40 } 41 42 bool unite(int x, int y) { 43 x = find(x); 44 y = find(y); 45 if(x != y) { 46 pre[x] = y; 47 return 1; 48 } 49 return 0; 50 } 51 52 void init() { 53 for(int i = 0; i < maxn; i++) { 54 pre[i] = i; 55 } 56 } 57 58 void clear() { 59 init(); 60 memset(e, 0, sizeof(e)); 61 A = 0, B = 0; 62 cnt = 0; 63 } 64 65 int main() { 66 // freopen("in", "r", stdin); 67 int T; 68 fib[0] = 0, fib[1] = 1, fib[2] = 1; 69 for(int i = 3; i <= 26; i++) { 70 fib[i] = fib[i-1] + fib[i-2]; 71 } 72 scanf("%d", &T); 73 for(int _ = 1; _ <= T; _++) { 74 printf("Case #%d: ", _); 75 clear(); 76 scanf("%d %d", &n, &m); 77 for(int i = 0; i < m; i++) { 78 scanf("%d %d %d", &e[i].u, &e[i].v, &e[i].w); 79 } 80 sort(e, e+m, cmp1); 81 for(int i = 0; i < m; i++) { 82 if(unite(e[i].u, e[i].v)) { 83 A += e[i].w; 84 cnt++; 85 } 86 } 87 if(cnt != n - 1) printf("No\n"); 88 else { 89 init(); 90 sort(e, e+m, cmp2); 91 for(int i = 0; i < m; i++) { 92 if(unite(e[i].u, e[i].v)) { 93 B += e[i].w; 94 cnt++; 95 } 96 } 97 int flag = 0; 98 for(int i = 1; i <= 25; i++) { 99 if(fib[i] <= B && fib[i] >= A) { 100 flag = 1; 101 break; 102 } 103 } 104 if(flag) printf("Yes\n"); 105 else printf("No\n"); 106 } 107 } 108 }
[HDOJ4786]Fibonacci Tree 最小生成树
标签:
原文地址:http://www.cnblogs.com/vincentX/p/4948065.html