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

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

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

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

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

 

# 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-9
# define MOD 1000000000
# define INF 1000000000
# 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<<1,l,mid
# define rch p<<1|1,mid+1,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=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
void Out(int a) {
    if(a<0) {putchar('-'); a=-a;}
    if(a>=10) Out(a/10);
    putchar(a%10+'0');
}
const int N=10005;
//Code begin...

struct Edge{int p, next;}edge[N<<1];
int head[N], cnt=1, 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]==-1||dfs(linker[v])) {linker[v]=u; return true;}
        }
    }
    return false;
}
int hungary(){
    int res=0;
    mem(linker,-1);
    FO(u,0,uN) {
        mem(used,0);
        if (dfs(u)) ++res;
    }
    return res;
}
int main ()
{
    int n, x;
    scanf("%d",&n); uN=n;
    FO(i,0,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,0,n) res[linker[i]]=i;
        FO(i,0,n) printf(i==0?"%d":" %d",res[i]);
        putchar('\n');
    }
    return 0;
}
View Code

 

posted @ 2017-04-28 15:01  free-loop  阅读(203)  评论(0编辑  收藏  举报