我是祝睿融。
T1
A.
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5, MOD = 1e8 - 3;
int n, c[N], t[N], ans;
pair<int, int> a[N], b[N];
int query (int x) {
int sum = 0;
while(x > 0) {
sum += t[x];
x -= (x & -x);
}
return sum;
}
void add (int x) {
while(x <= n) {
t[x]++;
x += (x & -x);
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i].first;
}
for (int i = 1; i <= n; i++) {
cin >> b[i].first;
}
for (int i = 1; i <= n; i++) {
a[i].second = b[i].second = i;
}
sort(a + 1, a + n + 1);
sort(b + 1, b + n + 1);
for (int i = 1; i <= n; i++) {
c[a[i].second] = b[i].second;
}
for (int i = 1; i <= n; i++) {
ans += query(n - c[i]);
ans %= MOD;
add(n - c[i] + 1);
}
cout << ans;
return 0;
} T2
A.
#include <bits/stdc++.h>
using namespace std;
const int N = 200010;
int tr[N], n, a[N];
void add(int x, int v) {
for (; x < N; x += x & -x) tr[x] += v;
}
int ask(int x) {
int res = 0;
for (; x; x -= x & -x) res += tr[x];
return res;
}
struct Node {
int id;
int v;
}b[N];
bool del[N];
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i]; b[i].id = i; b[i].v = a[i];
}
for (int i = 1; i <= n; i++) add(i, 1);
sort(b + 1, b + n + 1, [](const Node& a, const Node& b) { return a.v < b.v; });
int cur = 1;
long long ans = 0;
for (int i = 1; i <= n; i++) {
if (!del[i]) del[i] ^= 1, add(i, -1);
while (b[cur].v < i && cur <= n) {
if (!del[b[cur].id]) del[b[cur].id] ^= 1, add(b[cur].id, -1);
cur++;
}
ans += ask(min(n, a[i]));
}
cout << ans;
return 0;
}
T3
哦哦哦哦哦。
哦哦哦哦哦。T4
树上逆序对。
和逆序对非常相似 只需要处理出每条链上的逆序对数即可
处理时需要注意的问题: file 处理右子树时一定会将左子树的信息重复统计 这时候需要记录一个last值 一个小小的容斥思想即可
#include<bits/stdc++.h>
#define int long long
using namespace std;
int c[100100], data[100100], N, n, ans, maxi, head[100100], num[100100], lst[1001000];
struct edge {
int i, data;
} d[500010];
struct node {
int to, nex;
} e[1001000];
void add(int x, int y) {
e[++N].to = y;
e[N].nex = head[x];
head[x] = N;
}
void insert(int i, int ci) {
for (; i <= n; i += (i & -i)) c[i] += ci;
}
int query(int i) {
int sum = 0;
for (; i > 0; i -= (i & -i)) sum += c[i];
return sum;
}
bool cmp(edge a, edge b) {
if (a.data == b.data) return a.i < b.i;
return a.data < b.data;
}
int dfs(int now) {
insert(d[now].data, 1);
int D = query(n) - query(d[now].data);
for (int i = head[now]; i; i = e[i].nex) {
int to = e[i].to;
dfs(to);
}
num[now] += query(n) - query(d[now].data) - D;
}
bool cmp1(edge a, edge b) {
return a.data < b.data;
};
bool cmp2(edge a, edge b) {
return a.i < b.i;
};
signed main() {
cin >> n;
for (int i = 1; i <= n; i++) d[i].i = i, cin >> d[i].data;
sort(d + 1, d + n + 1, cmp1);
for (int i = 1; i <= n; i++) d[i].data = i;
sort(d + 1, d + n + 1, cmp2);
for (int i = 2; i <= n; i++) {
int x, y = i; cin >> x;
add(x, y);
}
dfs(1);
for (int i = 1; i <= n; i++) cout << num[i] << "\n";
return 0;
}