SGU101 - Domino(欧拉路)

思路:

把牌的两个数值抽象成有两个端点的路径,然后找到一个欧拉路径能够遍历所有的边即可。

代码如下:

#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
#define M 105
vector<int>g[10][10];
bool vis[M];
int n, du[10], ans[M];
int dfs(int cur, int x)
{
    if(cur==n+1) return 1;
    for(int i = 0; i <= 6; ++i)
    {
        for(int j = 0; j < (int)g[x][i].size(); ++j)
        {
            int l = g[x][i][j];
            l = l<0?-1*l:l;
            if(vis[l]==0)
            {
                vis[l] = 1;
                ans[cur] = g[x][i][j];
                if(dfs(cur+1,i)) return 1;
                vis[l] = 0;
                break;
            }
        }
    }
    return 0;
}
int main ()
{
    int a, b;
    scanf("%d",&n);
    for(int i = 1; i <= n; ++i)
    {
        scanf("%d %d",&a,&b);
        g[a][b].push_back(i);
        g[b][a].push_back(-i);
        ++du[a];
        ++du[b];
    }
    int st = 0, cnt = 0;
    for(int i = 0; i <= 6; ++i)
        if(du[i]) { st = i; break; }
    for(int i = 0; i <= 6; ++i)
        {  if(du[i]&1) {st = i; ++cnt;}  }
    if(cnt!=0&&cnt!=2) { printf("No solution\n"); return 0; }
    int f = dfs(1,st);
    if(f)
    {
        for(int i = 1; i <= n; ++i)
            printf("%d %c\n",(ans[i]<0?-1*ans[i]:ans[i]), (ans[i]<0?'-':'+'));
    }
    else printf("No solution\n");
    return 0;
}


你可能感兴趣的:(SGU101 - Domino(欧拉路))