欧拉回路

来源:互联网 发布:tv软件哪个好 编辑:程序博客网 时间:2024/04/27 14:49
//首先构造图,再判断它是不是欧拉回路图,若是,则输入回路//小回路汇总成最终回路#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 70 10 21 32 33 43 54 50 1 1 0 0 01 0 0 1 0 01 0 0 1 0 00 1 1 0 1 10 0 0 1 0 10 0 0 1 1 0Press any key to continue580 10 10 20 31 41 32 33 40 1 1 1 01 0 0 1 11 0 0 1 01 1 1 0 10 1 0 1 0这不是欧拉回路图570 10 20 31 41 32 33 4

0 0