HDU 4337 哈密顿回路模板题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Feynman1999/article/details/82318530

problem

I am the bone of my sword. Steel is my body, and the fire is my blood.
- from Fate / Stay Night
You must have known the legend of King Arthur and his knights of the round table. The round table has no head, implying that everyone has equal status. Some knights are close friends with each other, so they prefer to sit next to each other.

Given the relationship of these knights, the King Arthur request you to find an arrangement such that, for every knight, his two adjacent knights are both his close friends. And you should note that because the knights are very united, everyone has at least half of the group as his close friends. More specifically speaking, if there are N knights in total, every knight has at least (N + 1) / 2 other knights as his close friends.

Input

The first line of each test case contains two integers N (3 <= N <= 150) and M, indicating that there are N knights and M relationships in total. Then M lines followed, each of which contains two integers ai and bi (1 <= ai, bi <= n, ai != bi), indicating that knight ai and knight bi are close friends.

Output

For each test case, output one line containing N integers X1, X2, …, XN separated by spaces, which indicating an round table arrangement. Please note that XN and X1 are also considered adjacent. The answer may be not unique, and any correct answer will be OK. If there is no solution exists, just output “no solution”.

Sample Input

3 3
1 2
2 3
1 3
4 4
1 4
2 4
2 3
1 3

Sample Output

1 2 3
1 4 2 3

思路

题目条件等价于保证存在哈密顿回路

代码示例

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

const int maxn = 1000;
const int inf = 0x3f3f3f3f;

int n,m;
bool G[maxn][maxn];
int x[maxn];//记录回路中的第i个点

//下标从0开始
void hamilton()
{
    int k;
    bool s[maxn];
    for(int i=0;i<n;i++){
        x[i] = -1;
        s[i] = false;
    }
    k = 1;
    s[0] = true;
    x[0] = 0;
    while(k >= 0){
        x[k]++;
        while(x[k] < n){
            if(!s[x[k]] && G[x[k-1]][x[k]]) break;
            else x[k]++;
        }
        if((x[k] < n) && (k!= n-1)){
            s[x[k++]] = true;
        }
        else if((x[k] < n) && k==n-1 && G[x[k]][x[0]]) break;
        else{
            x[k] = -1;
            k--;
            s[x[k]] = false;
        }
    }
}

int main()
{
    while(scanf("%d%d",&n,&m) != EOF){
        memset(G,0,sizeof(G));
        memset(x,0,sizeof(x));
        for(int i=0;i<m;i++){
            int u,v;
            scanf("%d%d",&u,&v);u--;v--;
            G[u][v]=G[v][u]=true;
        }

        hamilton();

        for(int i=0;i<n;i++){
            if(i == n-1) printf("%d\n",x[i]+1);
            else printf("%d ",x[i]+1);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Feynman1999/article/details/82318530