//首先构造图,再判断它是不是欧拉回路图,若是,则输入回路
//小回路汇总成最终回路
#include <iostream>
using namespace std;
//012345分别表示v0 v1......
int v;//点数目
int edge;///边数目
int** draw();//绘图
void huilu(int **a,int go);//处理
int main(int argc, char const *argv[])
{
int**a=draw();
huilu(a,0);
//------------------------------------------------------------------------//
return 0;
}
int** draw()//绘图
{
int i,j;
cin>>v>>edge;///输入点数目和边数目
int **a=new int*[v];
for ( i = 0; i < v; ++i)
a[i]=new int[v];
for ( i = 0; i < v; ++i)
for ( j = 0; j < v; ++j)
a[i][j]=0;
int spot1,spot2;
for ( i = 0; i < edge; ++i)
{
cin>>spot1>>spot2;
a[spot1][spot2]++; a[spot2][spot1]++;
}
///-------------------------------------------------------------///
int puanduan=0;
for ( i = 0; i < v; ++i)
{
for ( j = 0; j < v; ++j)
{
cout<<a[i][j]<<" ";
puanduan+=a[i][j];
}
if (puanduan%2 != 0)//补充,没有判断连通分图
{cout<<"此图无欧拉回路";exit(1);}
puanduan=0;
cout<<"\n";
}
cout<<"\n";
return a;
}
void huilu(int **a,int go)
{
int i;
int lushu=0;//当前的边数
int *hui=new int[v*2];for(i = 0; i < v*2; ++i)hui[i]=-1;//汇总回路
int *temp=new int[v*2];for(i = 0; i < v*2; ++i)temp[i]=-1;//小回路
int hui_i=0,temp_i=-1;
i=go;
temp[++temp_i]=i;
hui[0]=go;
while(true)
{
while(true)
{
for (int j = 0; j < v; ++j)
{
if (a[i][j]>0)
{
temp[++temp_i]=j;
a[i][j]--;a[j][i]--;//去掉这条路
i=j;//沿路而走
break;
}
}
if (temp[0]==i)//小回路构成了,break
break;
}//下面把小回路接入汇总回路
int k,y,p;
for ( k = 0; hui[k] !=-1 ; ++k)//找到接入点
if (hui[k]==temp[0])
break;
for ( y = lushu-1; y>k; --y)//后移动,膨出位置
{
hui[y+temp_i]=hui[y];
}
for ( p = 1; p <= temp_i; ++p)//插入
{
hui[k+p]=temp[p];
}
lushu+=temp_i+1;
///---------------------------------------------------------//
for ( i = 0; i < v; ++i)找到下一个圈的开始点
for (int j = 0; j < v; ++j)
if (a[i][j]!=0)goto biao;
if(i==v)break;//说明所有边都收录了,ok了
biao:;
temp_i=-1;//重置
temp[++temp_i]=i;//小回路的开头
}
for ( i = 0; hui[i]!=-1; ++i)//输出回路
cout<<hui[i];
}
-----------------------------------------------------------//
//测试数据
6 7
0 1
0 2
1 3
2 3
3 4
3 5
4 5
0 1 1 0 0 0
1 0 0 1 0 0
1 0 0 1 0 0
0 1 1 0 1 1
0 0 0 1 0 1
0 0 0 1 1 0
Press any key to continue
5
8
0 1
0 1
0 2
0 3
1 4
1 3
2 3
3 4
0 1 1 1 0
1 0 0 1 1
1 0 0 1 0
1 1 1 0 1
0 1 0 1 0
这不是欧拉回路图
5
7
0 1
0 2
0 3
1 4
1 3
2 3
3 4
欧拉回路
最新推荐文章于 2024-04-08 10:47:27 发布