题解:AT_abc399_d [ABC399D] Switch Seats
题意翻译
给定一个长度为
求有多少对
1.
2.
3.执行以下操作任意次后可达到
有
题目解析
我们不难发现,满足第三个条件的数对
发现这个特性后,我们只需要记录与每个数相同的另外一个数在哪,就能
AC code
#include <bits/stdc++.h>
using namespace std;
//#define int long long
const int N = 2e5 + 5;
int t;
int n;
int a[2 * N];
int idx[N];
int ans = 0;
int pos[2 * N]; // 记录与ai相同的另一个数的位置
int main() {
cin >> t;
while (t--) { // 有多测
ans = 0; // 记录答案
memset(idx, 0, sizeof(idx)); // 初始化
scanf("%d", &n); // 输入
for (int i = 1; i <= 2 * n; ++i) {
scanf("%d", &a[i]);
if (!idx[a[i]]) {
idx[a[i]] = i;
}else {
pos[i] = idx[a[i]];
pos[idx[a[i]]] = i; // 计算位置
}
}
for (int i = 2; i <= 2 * n; ++i) {
if (a[i] == a[i - 1] || a[i] == a[i + 1]) { // 判断前两条条件
continue;
}
int x = pos[i], y = pos[i - 1];
if (a[y] == a[y - 1] || a[y] == a[y + 1]) {
continue;
}
if (abs(x - y) == 1) { // 判条件3
++ans; // 记录答案
}
}
printf("%d\n", ans / 2); // 由于会有两数相等,所以每次会多计算一次答案,要除以2
}
return 0;
}