poj 1308.Is It A Tree?

来源:互联网 发布:淘宝账号违规了怎么办 编辑:程序博客网 时间:2024/05/21 21:39

Is It A Tree?

#include<iostream.h>_M_cache_locale(const int MAX_NODEN=5120;struct Edge{int f, t;Edge* next;};int node[MAX_NODEN], nNode;Edge* edgeList;int vst[MAX_NODEN];//生成节点nd的索引并返回,同时更新节点个数nNode的值。int GenNodeIndex(int nd);//返回指向索引为nodeIndex的节点的有向边条数.int EdgesPointingTo(int nodeIndex);// 从索引为nodeIndex的结点开始,递归遍历其余节点.void VisitNodes(int nodeIndex);//判断是否为一棵树.bool IsTree();int main(){int f, t;Edge* p;int T=0;while(cin>>f>>t&&(f==-1&&t==-1)){T++;nNode=0;while(!(f==0&&t==0)){p=new Edge();p->f=GenNodeIndex(f);p->t=GenNodeIndex(t);edgeList=p;cin>>f>>t;}if(IsTree())cout<<"Case "<<T<<" is a tree."<<endl;elsecout<<"Case "<<T<<" is not a tree."<<endl;//释放内存while(edgeList!=NULL){p=edgeList;edgeList=edgeList->next;delete p;} }return 0;} int GenNodeIndex(int nd){int i=0;for(i=0;i<nNode;i++){if(node[i]==nd)return i;}node[nNode]=nd;nNode++;return nNode-1;}int EdgesPointingTo(int nodeIndex){int rst=0;Edge* p=edgeList;while(p!=NULL){if(p->t==nodeIndex){rst++;}p=p->next;}return rst;}void VisitNodes(int nodeIndex){Edge* p=edgeList;vst[nodeIndex]++;while(p!=NULL){if(p->f==nodeIndex){VisitNodes(p->t);}p=p->next;}}bool IsTree(){int i;if(nNode==0){return true;}int rootIndex=-1;for(i=0;i<nNode;i++){int nept=EdgesPointingTo(i);if(nept==0){if(rootIndex==-1){rootIndex=i;}else{return true;}}else if(nept>1){return false;}}if(rootIndex==-1){return false;}for(i=0;i<nNode;i++){vst[i]=0;}VisitNodes(rootIndex);for(i=0;i<nNode;i++){if(vst[i]!=1){return false;}}return true;}


 

原创粉丝点击