题解:P1053 [NOIP 2005 提高组] 篝火晚会
yingmuchen928 · · 题解
题目传送门
AC记录
1. 问题分析
1.合法性检查
首先需要检查是否存在一个排列使得每个同学的两个相邻愿望都能满足。
如果某个同学的愿望无法形成双向关系(即 a 希望和 b 相邻,但 b 不希望和 a 相邻),则直接返回 -1。
整个排列必须构成一个环,不能出现多个环或链式结构。
2.构造目标排列
从同学 1 开始,按照愿望关系构造目标排列 target。
如果构造过程中出现矛盾(如重复访问某个同学),说明无解。
3.计算最小交换代价
初始排列是 [ 1 , 2 , … , n ] [1,2,…,n],目标排列是 target。
每次交换可以移动若干个同学的位置(轮换),代价是参与交换的人数。
最小总代价 = n − 最大匹配数 ,其中最大匹配数是指初始位置和目标位置相同的同学的最大数量。
由于排列可以顺时针或逆时针旋转,需要分别计算两种情况下的匹配数。
2. 解题步骤
1.检查愿望合法性
对于每个同学 i,检查其两个愿望 a[i] 和 b[i]
是否互相关联(即 a[i] 的愿望是否包含 i,且 b[i] 的愿望是否包含 i)。
如果不满足,直接返回 -1。
2.构造目标排列
初始化 visited 数组,从同学 1 开始,按照愿望关系构造排列。
如果构造的排列长度 ≠
n,说明无解。
计算最小代价
计算初始排列 [ 1 , 2 , … , n ] [1,2,…,n] 和目标排列 target target 的偏移量(即 target[i] 应该在的位置)。
统计每个偏移量出现的次数,最大次数即为最大匹配数。
最小代价 = n − 最大匹配数 n−最大匹配数.
3. 代码实现(C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<pair<int, int>> wishes(n + 1);
for (int i = 1; i <= n; ++i) {
cin >> wishes[i].first >> wishes[i].second;
}
// 检查愿望是否合法
for (int i = 1; i <= n; ++i) {
int a = wishes[i].first, b = wishes[i].second;
if ((wishes[a].first != i && wishes[a].second != i) ||
(wishes[b].first != i && wishes[b].second != i)) {
cout << -1 << endl;
return 0;
}
}
// 构造目标排列
vector<int> target;
vector<bool> visited(n + 1, false);
int current = 1;
target.push_back(current);
visited[current] = true;
while (target.size() < n) {
int a = wishes[current].first;
int b = wishes[current].second;
if (!visited[a]) {
current = a;
} else if (!visited[b]) {
current = b;
} else {
// 无法继续构造,无解
cout << -1 << endl;
return 0;
}
target.push_back(current);
visited[current] = true;
}
// 检查首尾是否构成环
int first = target[0], last = target.back();
if (wishes[first].first != last && wishes[first].second != last) {
cout << -1 << endl;
return 0;
}
// 计算正向和反向的偏移量
vector<int> offset1(n), offset2(n);
for (int i = 0; i < n; ++i) {
offset1[(target[i] - (i + 1) + n) % n]++;
offset2[(target[i] + (i + 1)) % n]++;
}
int max_match = 0;
for (int i = 0; i < n; ++i) {
max_match = max(max_match, offset1[i]);
max_match = max(max_match, offset2[i]);
}
cout << n - max_match << endl;
return 0;
}