BZOJ 1562 变换序列(二分图匹配)

时间:2024-10-12 19:34:55

显然每个位置只有两个情况,所以用二分图最大匹配来求解。

如果二分图有完全匹配,则有解。

关键是如何求最小的字典序解。

实际上用匈牙利算法从后面开始找增广路,并优先匹配字典序小的即可。

# include <cstdio>
# include <cstring>
# include <cstdlib>
# include <iostream>
# include <vector>
# include <queue>
# include <stack>
# include <map>
# include <set>
# include <cmath>
# include <algorithm>
using namespace std;
# define lowbit(x) ((x)&(-x))
# define pi acos(-1.0)
# define eps 1e-
# define MOD
# define INF
# define mem(a,b) memset(a,b,sizeof(a))
# define FOR(i,a,n) for(int i=a; i<=n; ++i)
# define FO(i,a,n) for(int i=a; i<n; ++i)
# define bug puts("H");
# define lch p<<,l,mid
# define rch p<<|,mid+,r
//# define mp make_pair
# define pb push_back
typedef pair<int,int> PII;
typedef vector<int> VI;
# pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long LL;
int Scan() {
int x=,f=;char ch=getchar();
while(ch<''||ch>''){if(ch=='-')f=-;ch=getchar();}
while(ch>=''&&ch<=''){x=x*+ch-'';ch=getchar();}
return x*f;
}
void Out(int a) {
if(a<) {putchar('-'); a=-a;}
if(a>=) Out(a/);
putchar(a%+'');
}
const int N=;
//Code begin... struct Edge{int p, next;}edge[N<<];
int head[N], cnt=, res[N];
int linker[N], uN;
bool used[N]; void add_edge(int u, int v){edge[cnt].p=v; edge[cnt].next=head[u]; head[u]=cnt++;}
bool dfs(int u){
for (int i=head[u]; i; i=edge[i].next) {
int v=edge[i].p;
if (!used[v]) {
used[v]=true;
if (linker[v]==-||dfs(linker[v])) {linker[v]=u; return true;}
}
}
return false;
}
int hungary(){
int res=;
mem(linker,-);
FO(u,,uN) {
mem(used,);
if (dfs(u)) ++res;
}
return res;
}
int main ()
{
int n, x;
scanf("%d",&n); uN=n;
FO(i,,n) {
scanf("%d",&x);
int u=(i+x)%n, v=(i-x+n)%n;
if (u<v) swap(u,v);
if (u!=v) add_edge(i,v);
add_edge(i,u);
}
int ans=hungary();
if (ans!=n) puts("No Answer");
else {
FO(i,,n) res[linker[i]]=i;
FO(i,,n) printf(i==?"%d":" %d",res[i]);
putchar('\n');
}
return ;
}