hdu1325Is It A Tree?

來源:互聯網
上載者:User

題意:能否構成一棵樹。。怎麼感覺像圖論的知識,放在字串專題裡。

<code>

#include<stdio.h>
#include<iostream>
#include<string.h>
#define pr  printf
using namespace std;
int main()
{
   
    int i,j,k,m,n,T,ca,E,V,indeg,zero,root;
    int num,a[2][20],s,t,p,q;
    int D[20][20],degin[20],degout[20],have[20];
    ca=0;
    while(1)
    {
       for(i=1;i<20;i++)
       {
         degin[i]=degout[i]=0;//入度、出度
         have[i]=0;
         for(j=1;j<20;j++)
           D[i][j]=0;//i->j的邊
       }
       scanf("%d%d",&i,&j);
       if(i<0&&j<0)break;
       ca++;E=0;V=0;//E邊的條數,V點的個數
       while(1)
       {
          if(i==0&&j==0)break;
          E++;
          D[i][j]=1;
          degout[i]++;
          degin[j]++;
          if(have[i]==0)V++;//點個數
          if(have[j]==0)V++;
          have[i]=1;
          have[j]=1;
          scanf("%d%d",&i,&j);
      }
      if(E==0){pr("Case %d is a tree./n",ca); continue;}
      if(E!=V-1){pr("Case %d is not a tree./n",ca); continue;}
      zero=0;indeg=0; root=0;
      for(i=1;i<20;i++)
      {
         if(have[i])
         {
            if(degin[i]==0){zero++;root=i;}//找根結點
            if(degin[i]>1)indeg=2;// 不止一個指向i點,不是樹
           //pr("i=%d in=%d out=%d/n",i,degin[i],degout[i]);
         }
      }
      if(zero!=1||indeg==2){pr("Case %d is not a tree./n",ca); continue;}
      num=1;
      a[0][1]=root;
      s=0;
      p=0;q=1;t=1;
      while(1)
      {
         p=0;
         for(i=1;i<=q;i++)
         {
            for(j=1;j<20;j++)
           {
              if(D[a[s][i]][j]==1){p++;a[t][p]=j;}
           }
         }
         if(p==0)break;//所有都是葉子了
         q=p;//
         num+=p; //記錄加入這棵樹的點個數
         s=1-s;t=1-t;
      }
      if(num==V){pr("Case %d is a tree./n",ca); continue;}
      else        {pr("Case %d is not a tree./n",ca); continue;}
    }
    return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.