当前位置: 首页 > 工具软件 > Santa > 使用案例 >

D. Secret Santa

益光亮
2023-12-01

题目:https://codeforces.com/contest/1530/problem/D

Every December, VK traditionally holds an event for its employees named “Secret Santa”. Here’s how it happens.

n employees numbered from 1 to n take part in the event. Each employee i is assigned a different employee bi, to which employee i has to make a new year gift. Each employee is assigned to exactly one other employee, and nobody is assigned to themselves (but two employees may be assigned to each other). Formally, all bi must be distinct integers between 1 and n, and for any i, bi≠i must hold.

The assignment is usually generated randomly. This year, as an experiment, all event participants have been asked who they wish to make a gift to. Each employee i has said that they wish to make a gift to employee ai.

Find a valid assignment b that maximizes the number of fulfilled wishes of the employees.

Input
Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤105). Description of the test cases follows.

Each test case consists of two lines. The first line contains a single integer n (2≤n≤2⋅105) — the number of participants of the event.

The second line contains n integers a1,a2,…,an (1≤ai≤n; ai≠i) — wishes of the employees in order from 1 to n.

It is guaranteed that the sum of n over all test cases does not exceed 2⋅105.

Output
For each test case, print two lines.

In the first line, print a single integer k (0≤k≤n) — the number of fulfilled wishes in your assignment.

In the second line, print n distinct integers b1,b2,…,bn (1≤bi≤n; bi≠i) — the numbers of employees assigned to employees 1,2,…,n.

k must be equal to the number of values of i such that ai=bi, and must be as large as possible. If there are multiple answers, print any.

Example
input
2
3
2 1 2
7
6 4 6 2 4 5 6
output
2
3 1 2
4
6 4 7 2 3 5 1

题目大意:
给你一个序列,求出下标与下标对应的值不相同且不重复的数的个数,再把那些重复的数字改成其他不重复的数字。

思路:
定义一个包含1-n的集合把下标与下标对应的值不相同且不重复的数从集合里面删除,然后用集合里面剩下的数去填充,如果遇到下标与值相等的情况就跟第一个下标值交换

AC代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <set>
using namespace std;

int main() {

	int t;
	scanf("%d", &t);

	while (t--) {

		int n;
		scanf("%d", &n);


		vector<int> a(n), pos(n + 1), vis(n), used(n + 1);
		set<int> s;

		int tot = 0;
		for (int i = 0; i < n; i++) {
			
			scanf("%d", &a[i]);
			s.insert(i + 1);
			
		}

		for (int i = 0; i < n; i++) {

			if (!used[a[i]])
				used[a[i]] = vis[i] = 1, tot++,pos[a[i]] = i, s.erase(a[i]);
		}

		for (int i = 0; i < n; i++) {

			if (!vis[i]) {

				auto it = s.begin();

				if ((*it) != i + 1)
					a[i] = (*it), used[a[i]] = 1, pos[a[i]] = i;
				else {

					int id = pos[a[i]];
					a[i] = (*it);
					swap(a[i], a[id]);
					pos[a[i]] = i, pos[a[id]] = id;
				}
				s.erase(it);
			}
		}
		printf("%d\n", tot);
		for (int i = 0; i < n; i++)
			printf("%d ", a[i]);
		printf("\n");
	}
}
 类似资料:

相关阅读

相关文章

相关问答