首页 > 代码库 > hdu 4786 Fibonacci Tree (最小生成树扩展)

hdu 4786 Fibonacci Tree (最小生成树扩展)

///白边优先和黑边优先做两次最小生成树
///若有斐波那契树在这中间为yes
# include <stdio.h>
# include <algorithm>
# include <iostream>
# include <string.h>
# include <math.h>
using namespace std;
struct node
{
    int x;
    int y;
    int v;
};
struct node a[100010];
int father[100010];
bool cmp1(node a1,node a2)
{
    return a1.v<a2.v;
}
bool cmp2(node a1,node a2)
{
    return a1.v>a2.v;
}
int find(int x)
{
    if(father[x]==-1)
        return x;
    return father[x]=find(father[x]);
}
int main()
{
    int i,t,n,m,num;
    int cas=0;
    int f[30];
    f[1]=1;
    f[2]=2;
    for(num=3;; num++)
    {
        f[num]=f[num-1]+f[num-2];
        if(f[num]>100010)
            break;
    }
    while(~scanf("%d",&t))
    {
        while(t--)
        {
            scanf("%d%d",&n,&m);
            for(i=0; i<m; i++)
                scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].v);
            int min1=0;
            sort(a,a+m,cmp1);///黑边优先
            memset(father,-1,sizeof(father));
            for(i=0; i<m; i++)
            {
                int fa=find(a[i].x);
                int fb=find(a[i].y);
                if(fa!=fb)
                {
                    father[fa]=fb;
                    if(a[i].v==1)
                        min1++;
                }
            }
            int max1=0;
            sort(a,a+m,cmp2);///白边优先
            memset(father,-1,sizeof(father));
            for(i=0; i<m; i++)
            {
                int fa=find(a[i].x);
                int fb=find(a[i].y);
                if(fa!=fb)
                {
                    father[fa]=fb;
                    if(a[i].v==1)
                        max1++;
                }
            }
            int flag=0;
            for(i=1; i<=n; i++) ///判断是否连通
            {
                if(find(i)!=find(1))
                {
                    flag=1;
                    break;
                }
            }
            if(flag)
                printf("Case #%d: No\n",++cas);
            else
            {
                flag=0;
                for(i=1; i<=num; i++)
                {
                    if(f[i]>=min1&&f[i]<=max1)
                    {
                        flag=1;
                        break;
                    }
                }
                if(flag)
                    printf("Case #%d: Yes\n",++cas);
                else
                    printf("Case #%d: No\n",++cas);
            }

        }
    }
    return 0;
}

hdu 4786 Fibonacci Tree (最小生成树扩展)