Fibonacci Tree
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 47 Accepted Submission(s): 24
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 <= 10
5) and M(0 <= M <= 10
5).
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
Source
2013 Asia Chengdu Regional Contest
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long ll;
using namespace std;
struct edge
{
int u,v,w;
};
bool cmp0(edge b,edge a)
{
return b.w<a.w;
}
bool cmp(edge a,edge b)
{
return a.w>b.w;
}
const int N=100833,M=100033;
edge e[M];
int n,m;
int fb[226];
int f[N];
int F(int x){return f[x]==x?x:f[x]=F(f[x]);}
int mst()
{
int s=0,cnt=0;
for(int i=1;i<=n;i++)f[i]=i;
for(int i=0;i<m;i++)
{
int u=F(e[i].u);
int v=F(e[i].v);
if(u!=v)
{
cnt++;
f[u]=v;
s+=e[i].w;
if(cnt==n-1)break;
}
}
if(cnt<n-1)return -1;
return s;
}
int main()
{
fb[0]=1;fb[1]=2;
for(int i=2;i<30;i++)fb[i]=fb[i-1]+fb[i-2]; ///cout<<fb[29];
int t;cin>>t; ///cout<<fb[25];
int ca=1;
while(t--)
{
cin>>n>>m;
for(int i=0;i<m;i++)scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
sort(e,e+m,cmp0);
int s1=mst();
sort(e,e+m,cmp);
int s2=mst(); ///cout<<s1<<' '<<s2<<endl;
bool ok=0;
if(s1>s2)swap(s1,s2);
for(int i=0;i<=29;i++)
if(s1<=fb[i]&&fb[i]<=s2)
{
ok=1;break;
}
if(s1==-1)ok=0;
if(ok)printf("Case #%d: Yes\n",ca++);
else printf("Case #%d: No\n",ca++);
}
}