Fibonacci Tree
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2149 Accepted Submission(s): 682
Problem Description
Coach Pang is interested in Fibonacci numbers while Uncle Yang wants him to do some research on Spanning Tree. So Coach Pang decides to solve the following problem:
Consider a bidirectional graph G with N vertices and M edges. All edges are painted into either white or black. Can we find a Spanning Tree with some positive Fibonacci number of white edges?
(Fibonacci number is defined as 1, 2, 3, 5, 8, ... )
Input
The first line of the input contains an integer T, the number of test cases.
For each test case, the first line contains two integers N(1 <= N <= 105) and M(0 <= M <= 105).
Then M lines follow, each contains three integers u, v (1 <= u,v <= N, u<> v) and c (0 <= c <= 1), indicating an edge between u and v with a color c (1 for white and 0 for black).
Output
For each test case, output a line “Case #x: s”. x is the case number and s is either “Yes” or “No” (without quotes) representing the answer to the problem.
Sample Input
2 4 4 1 2 1 2 3 1 3 4 1 1 4 0 5 6 1 2 1 1 3 1 1 4 1 1 5 1 3 5 1 4 2 1
Sample Output
Case #1: Yes Case #2: No
这题要求生成树的 边权和 为 斐波那契值;
一个生成树构造成另一个生成树,可以不断的去边又加边来完成。 而这题全部边权为01,所以加边去边过程是+1 +1 的;
可以求出生成树 最大边权和 ,及最小的边权和。 然后枚举24个 小于100000的斐波那契数。
只要有某个斐波那契数 fb, fb<=最大边权和&&fb>=最小边权和 那就是可以构成这样一颗树的;
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; int f[100100]; int tt[25]; int find(int x){return x==f[x]?x:f[x] = find(f[x]);} //初始化为自己 void Union(int x, int y){ int fx = find(x), fy = find(y); if(fx == fy)return ; if(fx>fy) swap(fx,fy); f[fx] = f[x] = f[y] = fy;//这样 就可以直接查f[i] 判断祖先了 } struct path { int v,u,c; }; path lu[200100]; int cmp(path a,path b)// 白先 { return a.c>b.c; } int cmp2(path a,path b) { return a.c<b.c; } int main() { int i,t; int big,sml; tt[1]=1,tt[2]=2; for(i=3;;i++) { tt[i]=tt[i-2]+tt[i-1]; if(tt[i]>100000) break; } int cas=1; int u,v,n,m,flag; int x,y; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); for(i=0;i<m;i++) { scanf("%d%d%d",&lu[i].u,&lu[i].v,&lu[i].c); } flag=1; // 求大的 for(i=1;i<=n;i++) f[i]=i; sort(lu,lu+m,cmp); big=0; for(i=0;i<m;i++) { x=lu[i].v; y=lu[i].u; if(find(x)!=find(y)) { Union(x,y); big+=lu[i].c; } } for(i=1;i<=n;i++)// { if(find(i)!=find(1)) flag=0; } sml=0; for(i=1;i<=n;i++) f[i]=i; sort(lu,lu+m,cmp2); for(i=0;i<m;i++) { x=lu[i].v; y=lu[i].u; if(find(x)!=find(y)) { Union(x,y); sml+=lu[i].c; } } for(i=1;i<=n;i++)// { if(find(i)!=find(1)) flag=0; } printf("Case #%d: ",cas++); if(flag==0) { printf("No\n"); continue; } // printf("%d\n",tt[25]); flag=0; for(i=1;i<=24;i++) { if(tt[i]<=big&&tt[i]>=sml) flag=1; } if(flag) puts("Yes"); else puts("No"); } return 0; }