欧拉回路——欧拉路与欧拉回路
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了欧拉回路——欧拉路与欧拉回路相关的知识,希望对你有一定的参考价值。
题目:欧拉路与欧拉回路
描述:
给一个无向图图,如果存在欧拉回路请从第一个点为起点开始遍历,如果存在欧拉路,则以字典序大的为起点开始遍历,在遍历的过程中,字典序小的先遍历,都不存在输出-1。注意两个点之间可能有多条边,请全部遍历,还有可能存在自环。
【输入格式】
第一行N,E为点数和边数,后E行每行有两个数,表示他们之间存在一条无向边。
【输出格式】
若干个数,表示遍历次序。
【样例输入】
3 2
1 2
2 3
【样例输出】
3 2 1
【提示】
N<=20 E<=500
解析:最近刚学了欧拉路算法,于是刷了一波题目。这道题的名字看起来就很果,算法也很果。只是分别判一下走哪种路径而已。注意顶点标号不连续问题,经常被坑,好像成了此类题的一个重要坑(biao)点(zhi)。代码有点长。
AC代码:
![技术分享](https://image.cha138.com/20200613/3585dd26e1cc41a0ae10252e85debc68.jpg)
program zht; var n,m,i,p,max,tn,x,y,s:longint; d,bh:array[0..50] of longint; a:array[0..2000] of longint; map1,map2:array[0..50,0..50] of longint; procedure dfs1(x:longint); var i:longint; begin for i:=1 to n do if map1[x,i]>0 then begin dec(map1[x,i]); dec(map1[i,x]); dfs1(i); end; inc(tn); a[tn]:=x; end; procedure dfs2(x:longint); var i:longint; begin for i:=1 to n do if map2[x,i]>0 then begin dec(map2[x,i]); dec(map2[i,x]); dfs2(i); end; inc(tn); a[tn]:=x; end; procedure chuli1; var k:longint; begin k:=0; dfs1(1); for k:=tn downto 1 do write(a[k],‘ ‘); end; procedure chuli2; var k:longint; begin k:=0; dfs2(max); for k:=tn downto 1 do inc(bh[a[k]]); for k:=tn downto 1 do write(a[k],‘ ‘); end; begin assign(input,‘path_euler.in‘); assign(output,‘path_euler.out‘); reset(input); rewrite(output); readln(n,m); for i:=1 to m do begin readln(x,y); inc(map1[x,y]); inc(map1[y,x]); inc(map2[x,y]); inc(map2[y,x]); inc(d[x]); inc(d[y]); end; for i:=1 to n do if (d[i]=0) or (d[i] mod 2=1) then begin p:=1; break; end; for i:=1 to n do if d[i] mod 2=1 then begin if i>max then max:=i; inc(s); end; if (s<>2) and (p=1) then begin writeln(‘-1‘); exit; end; if p=0 then chuli1 else chuli2; close(input); close(output); end.
以上是关于欧拉回路——欧拉路与欧拉回路的主要内容,如果未能解决你的问题,请参考以下文章