UESTC 1970 咸鱼咸鱼咸

题目:http://www.qscoj.cn/#/problem/show/1970

 

本题就是求一个图的欧拉通路或者欧拉回路

用圈套圈算法跑一遍就行了

但是dfs的时候会爆栈,所以需要改成非递归形式

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
using namespace std;
const int N=4e6+5;
int head[N],to[N],nt[N],deg[N];
bool use[N];
int n,m,tot;
stack<int> st,st1;
void addedge(int u,int v)
{
    nt[++tot]=head[u];
    to[tot]=v;
    head[u]=tot;
}
void euler(int x)
{
    st1.push(x);
    while(!st1.empty())
    {
        int t=st1.top();
        st1.pop();
        st.push(t);
        for(int i=head[t];i!=-1;i=nt[i])
        {
            head[t]=nt[i];
            if (!use[i])
            {
                use[i]=use[i^1]=1;
                st1.push(to[i]);
                break;
            }
        }
    }
}
int main()
{
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        memset(head,-1,sizeof(head));
        memset(nt,-1,sizeof(nt));
        memset(use,0,sizeof(use));
        memset(deg,0,sizeof(deg));
        tot=-1;
        for(int i=1;i<=m;i++)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            addedge(x,y);
            addedge(y,x);
            deg[x]++;deg[y]++;
        }
        int s=0;
        int start=0;
        for(int i=0;i<n;i++)
            if (deg[i]&1)
            {
                s++;
                start=i;
            }
        if (s==0||s==2)
        {
            euler(start);
            printf("Yes\n%d",st.top());
            st.pop();
            while(!st.empty())
            {
                printf(" %d",st.top());
                st.pop();
            }
            printf("\n");
        }
        else printf("No\n");
    }
    return 0;
}

  

posted @ 2018-07-17 12:15  BK_201  阅读(224)  评论(0编辑  收藏  举报