Description
对于 (N) 个整数 (0, 1, cdots, N-1) ,一个变换序列 (T) 可以将 (i) 变成 (T_i) ,其中 (T_i in { 0,1,cdots, N-1}) 且 (igcup_{i=0}^{N-1} {T_i} = {0,1,cdots , N-1}) 。 (forall x,y in {0,1,cdots , N-1}) ,定义 (x) 和 (y) 之间的距离 (D(x,y)=min{|x-y|,N-|x-y|}) 。给定每个 (i) 和 (T_i) 之间的距离 (D(i,T_i)) ,你需要求出一个满足要求的变换序列 (T) 。如果有多个满足条件的序列,输出其中字典序最小的一个。
Solution
显然对于 (i) ,能建的边为 ((i,(i-a)mod~n)) 和 ((i,(i+a)mod~n)) 。建完图跑最大匹配就好了,若所有数都能匹配,则有解。
对于求字典序最小,我们加边时可以考虑后加字典序小的边,这样就能先访问到;并且匹配时从大到小枚举左部点。
Code
//It is made by Awson on 2018.3.15
#include <bits/stdc++.h>
#define LL long long
#define dob complex<double>
#define Abs(a) ((a) < 0 ? (-(a)) : (a))
#define Max(a, b) ((a) > (b) ? (a) : (b))
#define Min(a, b) ((a) < (b) ? (a) : (b))
#define Swap(a, b) ((a) ^= (b), (b) ^= (a), (a) ^= (b))
#define writeln(x) (write(x), putchar('
'))
#define lowbit(x) ((x)&(-(x)))
using namespace std;
const int N = 10000;
void read(int &x) {
char ch; bool flag = 0;
for (ch = getchar(); !isdigit(ch) && ((flag |= (ch == '-')) || 1); ch = getchar());
for (x = 0; isdigit(ch); x = (x<<1)+(x<<3)+ch-48, ch = getchar());
x *= 1-2*flag;
}
void print(int x) {if (x > 9) print(x/10); putchar(x%10+48); }
void write(int x) {if (x < 0) putchar('-'); print(Abs(x)); }
int n, a, vis[N+5], match[N+5], ans[N+5];
struct tt {int to, next; }edge[(N<<2)+5];
int path[N+5], top;
void add(int u, int v) {edge[++top].to = v, edge[top].next = path[u], path[u] = top; }
bool dfs(int o, int color) {
for (int i = path[o]; i; i = edge[i].next)
if (vis[edge[i].to] != color) {
vis[edge[i].to] = color;
if (match[edge[i].to] == -1 || dfs(match[edge[i].to], color)) {
match[edge[i].to] = o; return true;
}
}
return false;
}
void work() {
read(n); memset(match, -1, sizeof(match));
for (int i = 0; i < n; i++) {
read(a);
if ((i-a+n)%n > (i+a)%n) add(i, (i-a+n)%n), add(i, (i+a)%n);
else add(i, (i+a)%n), add(i, (i-a+n)%n);
}
for (int i = n-1; i >= 0; i--)
if (!dfs(i, i+1)) {puts("No Answer
"); return; }
for (int i = 0; i < n; i++) ans[match[i]] = i;
for (int i = 0; i < n-1; i++) write(ans[i]), putchar(' ');
writeln(ans[n-1]);
}
int main() {
work(); return 0;
}