hdu 4786 A - Fibonacci Tree

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

Case #1: Yes
Case #2: No

 问你图中存不存在一颗生成树的权值为斐波那契数,考虑两次kruskal求出最小和最大生成树的权值,如果他们之间有斐波那契数列,那就肯定存在

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn=2e5+100;
int fa[maxn],fi[maxn],n,m,maxx,minn,flag;
unordered_map<int,int>mp;
struct edge
{
	int u,v,w;
}e[maxn];
int cnt;
inline void addedge(int u,int v,int w)
{
	cnt++;
	e[cnt].u=u;
	e[cnt].v=v;
	e[cnt].w=w;
}
inline void fib()
{
	fi[1]=1;fi[2]=1;mp[fi[1]]=1;mp[fi[2]]=1;
	for(int i=3;i<=35;i++) {fi[i]=fi[i-1]+fi[i-2];if(fi[i]>100000)break;mp[fi[i]]=1;}
}
inline void init()
{
	cnt=minn=maxx=flag=0;
	memset(e,0,sizeof e);
}
int find(int x){return fa[x]==x?fa[x]:fa[x]=find(fa[x]);}
inline void kruskal()
{
	for(int i=1;i<=n;i++) fa[i]=i;int tot=0;
	sort(e+1,e+1+cnt,[](const edge &a,const edge &b){return a.w<b.w;});
	for(int i=1;i<=cnt;i++)
	{
		int x=find(e[i].u);int y=find(e[i].v);
		if(x!=y){fa[x]=y;minn+=e[i].w;tot++;}
		if(tot==n-1)break; 
	}
	if(tot!=n-1)minn=0;
	for(int i=1;i<=n;i++) fa[i]=i;tot=0;
	for(int i=cnt;i>=1;i--)
	{
		int x=find(e[i].u);int y=find(e[i].v);
		if(x!=y){fa[x]=y;maxx+=e[i].w;tot++;}
		if(tot==n-1)break; 
	}
	if(tot!=n-1)maxx=0;
}
int main()
{
	fib();
	int t;scanf("%d",&t);
	for(int cc=1;cc<=t;cc++)
	{
		init();
		scanf("%d%d",&n,&m);
		for(int i=0;i<m;i++)
		{
			int u,v,w;scanf("%d%d%d",&u,&v,&w);addedge(u,v,w);addedge(v,u,w);
		}
		kruskal();
		for(int i=minn;i<=maxx;i++)if(mp[i]){printf("Case #%d: Yes\n",cc);flag=1;break;}
		if(!flag)printf("Case #%d: No\n",cc);
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值