ABC436
E
题面
给定一个排列 \(P\),你能交换任意两个数,要求交换次数最少。问在最小交换次数下,第一次交换的两个数有多少种不同的情况
题解
容易发现,由 \(i\) 向 \(a_i\) 连边可形成置换环,有若干个置换环,考虑最优情况就是依次完成每个置换环排序归位,发现对于每个置换环,开始时可以选择任意两个数交换,因为交换后要么置换环大小 \(-1\),要么一分为二,答案就是 \(\sum_{该置换环} sz(sz-1)\)
code
click
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define out() (cout << "sb\n")
const int N = 3e5 + 5;
int n, a[N], pos[N];
bool vis[N];
int main() {
// system("fc .out .out");
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
IOS;
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i], pos[a[i]] = i;
ll ans = 0;
for (int i = 1; i <= n; i++) if (!vis[i]) {
int cnt = 0, cur = pos[i];
do {
cur = a[cur], cnt++, vis[cur] = 1;
// cout << cur << "\n";
} while (cur != pos[i]);
ans += 1ll * cnt * (cnt - 1) >> 1;
}
cout << ans << "\n";
return 0;
}
F
题面
给定一个长度为 \(n\) 的排列 \(a\),你可以选定一个端点为 \(l\sim r\) 的区间,并选择一个数 \(x\),删掉选定区间中 \(>x\) 的,请问有多少种选择后删掉删掉一些数所剩下的的不同的区间?
题解
结合样例分析,从左到右考虑排列的每个数 \(a_i\),指定选择的数 \(x \gets a_i\),我们会发现,选择的区间删掉一些数后不同的情况一共是 \((左边比它小的数+1)\times(右边比它小的数+1)\),然后就做完了。
code
click
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define out() (cout << "sb\n")
const int N = 5e5 + 5;
int n, a[N], bt[N];
void add(int pos, int x) {
for (int i = pos; i <= n; i += i & -i)
bt[i] += x;
}
int query(int pos) {
int ans = 0;
for (int i = pos; i >= 1; i -= i & -i) ans += bt[i];
return ans;
}
int main() {
// system("fc .out .out");
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
IOS;
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
ll ans = 0;
for (int i = 1; i <= n; i++) {
add(a[i], 1);
int v = query(a[i]);
ans += 1ll * v * (a[i] - v + 1);
}
cout << ans << "\n";
return 0;
}

浙公网安备 33010602011771号