poj2230(欧拉路)

欧拉路:

经过且不重复经过无向连通图的每一条边的路径

判断方法:有两个点的度为奇数其余点度数为偶数的无向连通图

欧拉回路;

经过且不重复经过无向连通图的每一条边的路径,并且能回到原点

判断方法:全部点度数为偶数的无向连通图

欧拉图

欧拉回路构成的图

输出路径方法

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int head[10010], ver[100010], Next[100010], tot; // 邻接表
int stack[100010], ans[100010]; // 模拟系统栈,答案栈
bool vis[100010];
int n, m, top, t;

void add(int x, int y) {
    ver[++tot] = y, Next[tot] = head[x], head[x] = tot;
}

void euler() {
    stack[++top] = 1;
    while (top > 0) {
        int x = stack[top], i = head[x];
        // 找到一条尚未访问的边
        while (i && vis[i]) i = Next[i];
        // 沿着这条边模拟递归过程,标记该边,并更新表头
        if (i) {
            stack[++top] = ver[i];
            head[x] = Next[i];
            // vis[i] = vis[i ^ 1] = true;
        }        
        // 与x相连的所有边均已访问,模拟回溯过程,并记录
        else {
            top--;
            ans[++t] = x;
        }
    }
}

int main() {
    cin >> n >> m;
    tot = 1;
    for (int i = 1; i <= m; i++) {
        int x, y;
        scanf("%d%d", &x, &y);
        add(x, y), add(y, x);
    }
    euler();
    for (int i = t; i; i--) printf("%d
", ans[i]);
}
#include<cstdio>
#include<algorithm>
using namespace std;

struct my{
       int v,next;
};

const int maxn=10000+10;
const int maxm=100000+10;

int adj[maxn],fa,n,m,Stack[maxm],ans[maxm];
my bian[maxm];
bool vis[maxm];

void myinsert(int u,int v){
     bian[++fa].v=v;
     bian[fa].next=adj[u];
     adj[u]=fa;
}

int main(){
    int u,v;
    fa=1;
    scanf("%d%d",&n,&m);
    for (int i=1;i<=m;i++){
        scanf("%d%d",&u,&v);
        myinsert(u,v);
        myinsert(v,u);
    }
    int top=0;
    int x,i;
    Stack[++top]=1;
    int t=0;
    while(top>0){
        x=Stack[top];
        i=adj[x];
        //while(i&&vis[i]) i=bian[i].next;
        v=bian[i].v;
        if(i){
            Stack[++top]=v;
            adj[x]=bian[i].next;
        }
        else {
            ans[++t]=x;
            top--;
        }
    }
   for (int j=t;j>=1;j--) printf("%d
",ans[j]);
return 0;
}
原文地址:https://www.cnblogs.com/lmjer/p/9372096.html