题意:n个人互相送礼物,每人送出一个 收到一个,不可以送给自己,给出一个数组,表示第i个人想送给ai,ai=0表示不知道送给谁。给出一个可行方案。
分析:
1.用vt,vt1分别保存 不知道送给谁的序号 和 没有收到礼物的序号
2.最精髓最重要的一步操作,用random_shuffle对vt1随机排序,然后cheak,如果不行就继续随机.
Code:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define mem(a, b) memset(a, b, sizeof(a));
#define lowbit(x) (x & -x)
#define lrt nl, nr, rt << 1
#define rrt nl, nr, rt << 1 | 1
#define IOS \
ios::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0);
const ll Inf = 9223372036854775807;
const int inf = 0x3f3f3f3f;
const int maxn = 2e5 + 5;
int vis[maxn];
int an[maxn];
vector<int> vt; //没送
vector<int> vt1; //没收
bool cheak() {
for (int i = 0; i < vt.size(); i++) {
if (vt[i] == vt1[i])
return 0;
}
return 1;
}
int main(void) {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> an[i];
vis[an[i]] = 1;
if (an[i] == 0)
vt.push_back(i);
}
for (int i = 1; i <= n; i++) {
if (!vis[i])
vt1.push_back(i);
}
while (!cheak())
random_shuffle(vt1.begin(), vt1.end());
for (int i = 0; i < vt.size(); i++)
an[vt[i]] = vt1[i];
for (int i = 1; i <= n; i++)
cout << an[i] << " ";
cout << endl;
return 0;
}