CF1283C. Friends and Gifts

Friends and Gifts

題意: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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章