View Code
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxnode = 50;
const int maxedge = 2000;
struct edge
{
int start;
int end;
};
edge ArrayEdge[maxedge];
int degree[maxnode];
int start;
int NodeNum, EdgeNum;
int anStack[maxedge], pIndex;
int visited[maxedge];
bool Judge()
{
for(int i=1; i<=NodeNum; ++i)
{
if(degree[i]&1 != 0)
{
return false;
}
}
return true;
}
void euler(int s)
{
for(int i=1; i<=EdgeNum; ++i)
{
if(!visited[i] && (ArrayEdge[i].start==s || ArrayEdge[i].end==s))
{
visited[i] = 1;
euler(ArrayEdge[i].start + ArrayEdge[i].end - s);
anStack[pIndex++] = i;
}
}
}
int main()
{
int x, y, z;
while(cin>>x>>y && (x!=0 || y!=0))
{
NodeNum = 0;
EdgeNum = 0;
memset(degree, 0, sizeof(degree));
memset(visited, 0, sizeof(visited));
pIndex = 0;
start = min(x, y);
do
{
cin>>z;
ArrayEdge[z].start = x;
ArrayEdge[z].end = y;
degree[x]++;
degree[y]++;
EdgeNum++;
NodeNum = max(NodeNum, max(x, y));
}while(cin>>x>>y && (x!=0 || y!=0));
if(!Judge())
cout<<"Round trip does not exist."<<endl;
else
{
euler(start);
for(int i=EdgeNum-1; i>=1; --i)
{
cout<<anStack[i]<<" ";
}
cout<<anStack[0]<<endl;
}
}
return 0;
}
第一次用用邻接表存储一个图,唉,说起来,自己也太不灵活了,题目要求输出的是边,可是我用邻接表存储的是每一个节点,这样不仅耗内存,而且慢了好多。
算了,也挺安慰的,没什么大的错误,就是用邻接表的时候指针指得有点晕了,很乱;
不过,额,该骂一下自己,题目都没看清楚,明明已经说了是连通图了,我还用并查集判断了一遍,不过已经删了
有俩个代码,效率差不了多少,就是开内存上的差距太大了,十倍左右
#include<iostream> #include<string> #include<stdlib.h> using namespace std; int d[45],n,m,s[2000],l; bool vis[2000]; typedef struct edge { int x,num; edge *next1; }e,*e1; struct node { e1 next2; }nod[45]; void init() { memset(d,0,sizeof(d)); for(int i=0;i<=44;i++) nod[i].next2=NULL; } void insert(int v,int w,int t) { e1 root=nod[v].next2,p1,p2; if(root->next1==NULL) { root->next1=(e1)malloc(sizeof(e)); root->next1->num=t; root->next1->x=w; root->next1->next1=NULL; } else { p1=(e1)malloc(sizeof(e)); p1->num=t;p1->x=w;p1->next1=NULL; e1 p=root->next1;p2=root; int flag=0; for( ;p!=NULL;p=p->next1) { if(p->num>t)//这里做了很多余的一件事 { p2->next1=p1; p1->next1=p; flag=1; break; } p2=p; } if(!flag) p2->next1=p1; } } void dfs(int v) { e1 p=nod[v].next2->next1; for(;p;p=p->next1) { if(!vis[p->num]) { vis[p->num]=1; dfs(p->x); s[l++]=p->num; } } } int main() { int t; while(cin>>n>>m&&(n||m)) { init(); while(n||m) { cin>>t; if(nod[n].next2==NULL) { nod[n].next2=(e1)malloc(sizeof(e)); nod[n].next2->next1=NULL; } if(nod[m].next2==NULL) { nod[m].next2=(e1)malloc(sizeof(e)); nod[m].next2->next1=NULL; } insert(n,m,t); insert(m,n,t); d[n]++;d[m]++; cin>>n>>m; } int flag=1; for(int i=1;i<45;i++) { if(d[i]&&d[i]%2!=0) { flag=0; break; } } if(flag) { memset(vis,0,sizeof(vis)); l=0; dfs(1); for(int i=l-1;i>=0;i--) cout<<s[i]<<' '; cout<<endl; continue; } else cout<<"Round trip does not exist."<<endl; } return 0; }