icontofig | 发布于 2019-02-05 23:39:39 | 阅读量 417 | A* 贪心

# Description

Piegirl found the red button. You have one last chance to change the inevitable end.
The circuit under the button consists of n nodes, numbered from 0 to n - 1. In order to deactivate the button, the n nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node i, the next node to be disarmed must be either node (2·i) modulo n or node (2·i) + 1 modulo n. The last node to be disarmed must be node 0. Node 0 must be disarmed twice, but all other nodes must be disarmed exactly once.
Your task is to find any such order and print it. If there is no such order, print -1.

## Input

Input consists of a single integer n (2 ≤ n ≤ 105).

## Output

Print an order in which you can to disarm all nodes. If it is impossible, print -1 instead. If there are multiple orders, print any one of them.

## Examples

`2`

`0 1 0`

`3`

`-1`

`4`

### Output

`0 1 3 2 0`

`16`

### Output

`0 1 2 4 9 3 6 13 10 5 11 7 15 14 12 8 0`

A*搜索+贪心

# 代码示例

```#include
using namespace std;
const int maxn = 2e5+5;
int mx = 0;
struct edge{
int fr,to,next1,next2;
}e[maxn<<1];
int h[maxn],d[maxn],pr[maxn];
int vis[maxn];
void init(){
memset(h,-1,sizeof(h));
memset(pr,-1,sizeof(pr));
return;
}
int cnt = 0;
void add(int u,int v){
e[cnt].fr = u;e[cnt].to = v;e[cnt].next1 = h[u];e[cnt].next2 = pr[v];
h[u] = pr[v] = cnt++;
return;
}
int inq[maxn];
int f[maxn];
void a_star_pre(){
queue<int>q;
q.push(0);
f[0] = 0;
inq[0] = 1;
while(!q.empty()){
int x = q.front();
q.pop();
for(int i = pr[x];i != -1;i = e[i].next2){
if(e[i].fr != 0 && inq[e[i].fr] == 0){
f[e[i].fr] = f[x] + 1;
inq[e[i].fr] = 1;
q.push(e[i].fr);
}
}
}
return;
}
int ans[maxn];
void find(int x){
vis[x]++;
int pos = -1,mxl = 2147483647;
for(int i = h[x];i != -1;i = e[i].next1){
if(vis[e[i].to] && e[i].to != 0)continue;
if(pos == -1){
pos = e[i].to;
mxl = f[e[i].to];
}
else{
if(mxl < f[e[i].to]){
pos = e[i].to;
mxl = f[e[i].to];
}
}
}
if(pos == -1)return;
ans[++cnt] = pos;
find(pos);
return;
}
int n;
int main(){
init();
cin >> n;
for(int i = 0;i < n;++i){
int x = (2*i)%n;
int y = (2*i+1)%n;
}
a_star_pre();
cnt = 0;
ans[++cnt] = 0;
find(0);
if(cnt != n+1){
cout << -1 << endl;
return 0;
}
else{
for(int i = 1;i <= cnt;++i)
cout << ans[i] << " ";
cout << endl;
}
return 0;
}﻿​```

417 人读过

0 条评论