Description

Input

Output

Sample Input
5
1 1 2 2 1
1 1 2 2 1
Sample Output
1 2 4 0 3
HINT
30%的數據中N≤50;
60%的數據中N≤500;
100%的數據中N≤10000。
Source
這題是二分圖應該不難看出來。
對于原序列中的一個點,對應兩個可匹配的點。
關鍵是怎么保證字典序最小
如果是暴力刪邊+匈牙利的話是$O(n^3)$的。
這里有兩種解決方法:
1.強制讓$x$號點連向字典序小的點,對失配的點重新匹配
2.將所有邊按照字典序排序,優先選擇最小的。
同時在匈牙利的時候從最大的往最小的枚舉
? ? 這實際上利用了匈牙利“搶” 的思想。
? ? 如之前的已經匹配過,那么字典序小的會搶字典序大的匹配。同時又因為每次選的是字典序最小的。因此答案可以保證是最優的。
#include<cstdio> #include<vector> #include<algorithm> #include<cstring> const int INF = 1e9 + 10, MAXN = 1e5 + 10; using namespace std; inline int read() {char c = getchar(); int x = 0, f = 1;while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();return x * f; } int N; int a[MAXN]; int match[MAXN], vis[MAXN], cur; vector<int> v[MAXN]; void AddEdge(int x, int y) {v[x].push_back(y); v[y].push_back(x); } bool Argue(int x) {for(int i = 0; i < v[x].size(); i++) {int to = v[x][i];if(vis[to] == cur) continue;vis[to] = cur; if(match[to] == -1 || Argue(match[to])) {match[to] = x;return true;}}return false; } void Hug() {int ans = 0;for(int i = N - 1; i >= 0; i--) {cur++;if(!Argue(i)) {printf("No Answer"); exit(0);}} for(int i = 0; i < N; i++) match[match[i + N]] = i;for(int i = 0; i < N; i++) printf("%d ", match[i]); } main() { #ifdef WIN32freopen("a.in", "r", stdin);freopen("a.out", "w", stdout); #endifmemset(match, -1, sizeof(match));N = read();for(int i = 0; i < N; i++) {int x = read();AddEdge(i, (i + x) % N + N);AddEdge(i, (i - x + N) % N + N);}for(int i = 0; i < N << 1; i++) sort(v[i].begin(), v[i].end());Hug(); }
?