码迷,mamicode.com
首页 > 其他好文 > 详细

sgu 101 无向图有双重边的欧拉路径

时间:2016-03-27 09:46:44      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
const int MAXN = 400 + 10;
struct Edge
{
    int to, next;
}edge[MAXN];
int tot, head[MAXN];
int vis[MAXN], degree[MAXN];
int N;
void addedge(int u, int v)
{
    edge[tot].to = v;
    edge[tot].next = head[u];
    head[u] = tot++;
}
void init()
{
    tot = 0;
    memset(head, -1, sizeof(head));
    memset(degree, 0, sizeof(degree));
    memset(vis, 0, sizeof(vis));
}
void dfs1(int u)
{
    vis[u] = 1;
    for(int i=head[u];i!=-1;i=edge[i].next)
    {
        int v = edge[i].to;
        if(!vis[v]) dfs1(v);
    }
}
int cc;
int ans[MAXN][2];
void dfs2(int u)
{
    for(int i=head[u];i!=-1;i=edge[i].next)
    {
        if(!vis[i])
        {
            vis[i] = 1;
            vis[i^1] = 1;
            int v = edge[i].to;
            dfs2(v);
            if(i %2 == 0) ans[cc++][0] = i / 2 + 1;
            else ans[cc++][1] = i / 2 + 1;
        }
    }
}
int main()
{
    while(scanf("%d", &N)!=EOF)
    {
        int u, v;
        init();
        int root;
        for(int i=1;i<=N;i++)
        {
            scanf("%d%d", &u, &v);
            root = u;
            addedge(u, v); addedge(v, u);
            degree[u]++; degree[v]++;
        }
        int count = 0; int flag = 1;
        int st;
        for(int i=0;i<=6;i++) if(degree[i] & 1)
        {
            count++;
            st = i;
        }
        if(!(count == 0 || count == 2)) flag = 0;
        else
        {
            dfs1(root);
            for(int i=0;i<=6;i++) if(degree[i] > 0 && !vis[i])
            {
                flag = 0;
                break;
            }
        }
        if(!flag)
        {
            printf("No solution\n");
            continue;
        }
        memset(vis, 0, sizeof(vis));
        if(count == 0)
        {
            dfs2(root);
        }
        else dfs2(st);
        for(int i=cc-1;i>=0;i--)
        {
            if(ans[i][0])
            {
                printf("%d +\n", ans[i][0]);
            }
            else printf("%d -\n", ans[i][1]);
        }
    }
    return 0;
}

sgu 101 无向图有双重边的欧拉路径

标签:

原文地址:http://www.cnblogs.com/mengfanrong/p/5324938.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!