CodeForces 325 E.The Red Button(欧拉回路)

Description

n 个节点0~ n1 ,点 i 可以到2i mod n (2i)+1 mod n ,求一条从 0 开始的哈密顿回路

Input

一个整数n(2n105)

Output

如果有解则输出该哈密顿回路,否则输出 1

Sample Input

2

Sample Output

0 1 0

Solution

n 为奇数时,到0点的点只有 0 n12,显然不能从 0 0,故只有从 n12 0 ,到n1的点也只有 n1 n12 n1 也不能到 n1 ,故只有从 n12 n1 ,但是 n12 只能到一个点,故不能满足哈密顿回路每个点都被经过一次的要求,故无解

n 为偶数时,由于第i个点可以到 2i 2i+1 ,而 i+n2 也是到 2i 2i+1 ,把 2i 2i+1 看作一个集合,原图中 u v的边变成现在 u 所在集合到v所在集合的边,那么新图中,每个点的入度和出度都是 2 ,该图必然存在欧拉回路,且该图的欧拉回路对应回原图就是原图的哈密顿回路,实现的时候,注意到本来i 2i 2i+1 是两条边,但是在新图中只是 i 所在集合到2i所在集合的一条边,故求新图欧拉回路本应标记这条集合之间的边,对应到原图直接标记 i <script type="math/tex" id="MathJax-Element-64">i</script>点即可

Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=100005;
int n,vis[maxn],ans[maxn],res;
void dfs(int u)
{
    if(vis[u])return ;
    vis[u]=1;
    dfs(2*u%n);
    dfs((2*u+1)%n);
    ans[res++]=u;
}
int main()
{
    scanf("%d",&n);
    if(n&1)printf("-1\n");
    else 
    {
        res=0;
        dfs(0);
        for(int i=res-1;i>=0;i--)printf("%d ",ans[i]);
        printf("0\n");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值