好吧这两道题题目描述什么的都一模一样。。。但是经过我亲身体验哈 这更本就是两道不同的题目。。。比如说 1 2 3 2 0 0这组测试样例,在POJ上AC的代码显示这是一棵树但是在HDU上AC的代码却显示这不是一棵树,这说明了什么呢?这两个不同的OJ对这道题目的理解并不相同,POJ不强调方向,二HDU强调方向,所以这两个OJ对题目不同的理解导致了同样的题目描述,但是实质上却是两道题。对树的判断只要排除重边,森林,自环以及特判一下空树的情况就好了,HDU上还要注意方向的判断,就是输入的前一个节点是后一个节点的父亲,先是POJ上AC的代码:
#include<stdio.h>
#include<string.h>
int father[1000],judge[1000],charge[1000];
int find(int x){
if(father[x]==x) return x;
else{
return father[x]=find(father[x]);
}
}
void unite(int x,int y){
int xx=find(x);
int yy=find(y);
if(xx==yy) return;
else
father[xx]=yy;
return;
}
int main(){
int x,y;
int i,j,k;
int yes,num,ju,line;
line=1;
while(1){
memset(judge,0,sizeof(judge));
memset(charge,0,sizeof(charge));
for(i=1;i<=1000;i++) father[i]=i;
yes=0;
i=0;
while(1){
scanf("%d%d",&x,&y);
if(x<0&&y<0) return 0;
if(x==0&&y==0) break;
if(charge[x]==0){
judge[i]=x;
charge[x]=1;
i++;
}
if(charge[y]==0){
judge[i]=y;
charge[y]=1;
i++;
}
if(find(x)==find(y)) yes=1;
unite(x,y);
}
ju=-1;
num=0;
for(j=0;j<i;j++){
if(father[judge[j]]==judge[j]&&judge[j]!=ju){
num++;
ju=judge[j];
}
}
if(yes==0){
if(num<=1){
printf("Case %d is a tree.\n",line);
}
else{
printf("Case %d is not a tree.\n",line);
}
}
else if(yes==1){
printf("Case %d is not a tree.\n",line);
}
line++;
}
return 0;
}
然后是HDU上AC的代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
int father[1000],judge1[1000],judge2[1000];
int find(int x){
if(x==father[x]) return x;
else
return father[x]=find(father[x]);
}
void unite(int x,int y){
int xx=find(x);
int yy=find(y);
if(xx==yy) return;
else
father[yy]=xx;
return;
}
void init(){
memset(judge1,0,sizeof(judge1));
memset(judge2,0,sizeof(judge2));
for(int i=0;i<=1000;i++) father[i]=i;
}
int main(){
int x,y;
int num=1;
int i,j,k;
int yes;
while(1){
init();
yes=0;
for(i=0;;i++){
scanf("%d%d",&x,&y);
if(x==0||y==0) break;
judge1[i]=x;
judge2[i]=y;
if(x<0&&y<0) return 0;
if(father[y]==y){
unite(x,y);
}
else if(father[y]!=y){
yes=1;
}
}
int ans=0;
int ju;
for(j=0;j<i;j++){
if(father[judge1[j]]==judge1[j]&&judge1[j]!=ju){
ans++;
ju=judge1[j];
//printf("%d %d\n",judge1[j],father[judge1[j]]);
}
if(father[judge2[j]]==judge2[j]&&judge2[j]!=ju){
ans++;
ju=judge2[j];
//printf("%d %d\n",judge2[j],father[judge2[j]]);
}
}
if(yes==0){
if(ans==1)
printf("Case %d is a tree.\n",num);
else{
printf("Case %d is not a tree.\n",num);
// printf("%d\n",ans);
}
}
else if (yes==1)
printf("Case %d is not a tree.\n",num);
num++;
}
return 0;
}
今天看了HDU1272 顿时觉得好眼熟,原来是做过的,不是很想做贴了HDU的1325WA了。。。但是啊POJ的代码果断就A了。。。。我真实凌乱了。。。。就是把我POJ的代码中间数组开大点就好。。。