关于本题
查看原帖
关于本题
503792
Svemit楼主2023/7/16 16:56

本题是否可以采取cdq分治?自己乱写了一个没过但是感觉挺对的(感觉应该是我写错了

#include <bits/stdc++.h>
#define a first
#define b second
using namespace std;
typedef long long LL;
const int N = 1e5 + 5, INF = 0x3f3f3f3f;
const LL mod = 1e9 + 7;
int n, res;
pair<int, int> p[N], tmp[N];
int c[N];
void modify(int x, int v) {for(; x <= n; x += x & -x) c[x] += v;}
int query(int x){int res = 0; for(; x; x -= x & -x) res += c[x]; return res;}
void cdq(int l, int r)
{
	if(l >= r) return;
	
	int mid = l + r >> 1, i = l, j = mid + 1, cur = l;
	cdq(l, mid), cdq(mid + 1, r);
	while(j <= r) modify(p[j].a, 1), j ++;
	while(i <= mid) res += query(p[i].b - 1), i ++;
	j = mid + 1;
	while(j <= r) modify(p[j].a, -1), j ++;
	i = l, j = mid + 1;
	while(i <= mid && j <= r) 
		if(p[i].b <= p[j].b) tmp[cur ++] = p[i ++];
		else tmp[cur ++] = p[j ++];
	while(i <= mid) tmp[cur ++] = p[i ++];
	while(j <= r) tmp[cur ++] = p[j ++];
	for(i = l; i <= r; i ++) p[i] = tmp[i];
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cin >> n;
	for(int i = 1; i <= 2 * n; i ++)
	{
		int x;
		cin >> x;
		if(!p[x].a) p[x].a = i;
		else p[x].b = i;
	}
	sort(p + 1, p + 1 + n);
	cdq(1, n);
	cout << res << '\n';
    return 0;
}
2023/7/16 16:56
加载中...