您的位置:首页 > 其它

并查集-Is It A Tree?hdu 1325

2012-03-31 17:26 316 查看
题目连接http://acm.hdu.edu.cn/showproblem.php?pid=1325

http://poj.org/problem?id=1308

在POJ上WA了,看来还是有问题的呀

#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
int
hr[100003],hs[100003];
int
mer[100003];
int
main()
{

// freopen("in.txt","r",stdin);
int n,m,i,flag,t=1,cn;

while
(scanf("%d%d",&n,&m))
{

if
(n<0&&m<0)
break
;
if
(n==0&&m==0)
{
printf("Case %d is a tree.\n",t++);continue;}
flag=1;cn=0;
memset(hr,0,sizeof(hr));
memset(hs,0,sizeof(hs));
memset(mer,0,sizeof(mer));
if
(hr[n]==0)
cn++;
if
(hr[m]==0)
cn++;
hr[n]=1;
hr[m]=1;
hs[m]++;
mer[m]=n;
cn--;
while
(scanf("%d%d",&n,&m),n||m)
{

if
(flag==0)
continue
;
if
(hr[n]==0)
cn++;
if
(hr[m]==0)
cn++;
hr[n]=1;
hr[m]=1;
hs[m]++;
if
(hs[m]>1)
{
flag=0;continue;}
while
(mer[n]>0)
n=mer[n];
while
(mer[m]>0)
m=mer[m];
if
(m==n)
{
flag=0;continue;}
mer[m]=n;
cn--;
}

if
(flag&&cn!=1)
flag=0;
if
(flag)
printf("Case %d is a tree.\n",t++);
else

printf("Case %d is not a tree.\n",t++);
}

return
0;
}


//去POJ看了下,发现自己漏掉了一种情况(其实有想过这种情况,就是自己以为不会出现,唉)

#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
int hr[100003],hs[100003];
int mer[100003];
int main()
{
//freopen("in.txt","r",stdin);
int n,m,i,flag,t=1,cn;

while(scanf("%d%d",&n,&m))
{
if(n<0&&m<0)
break;
if(n==0&&m==0)
{printf("Case %d is a tree.\n",t++);continue;}
flag=1;cn=0;
memset(hr,0,sizeof(hr));
memset(hs,0,sizeof(hs));
memset(mer,0,sizeof(mer));
if(hr
==0)
cn++;
if(hr[m]==0)
cn++;
if(m==n)//开始少了这一步、、、树不能自己指向自己呀
flag=0;
hr
=1;
hr[m]=1;
hs[m]++;
mer[m]=n;
cn--;
while(scanf("%d%d",&n,&m),n||m)
{
if(flag==0)
continue;
if(hr
==0)
cn++;
if(hr[m]==0)
cn++;
hr
=1;
hr[m]=1;
hs[m]++;
if(hs[m]>1||m==n)//还有这里,说明hduOJ测试数据还是不怎么强的
{ flag=0;continue;}
while(mer
>0)
n=mer
;
while(mer[m]>0)
m=mer[m];
if(m==n)
{ flag=0;continue;}
mer[m]=n;
cn--;
}
if(flag&&cn!=1)
flag=0;
if(flag)
printf("Case %d is a tree.\n",t++);
else
printf("Case %d is not a tree.\n",t++);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: