USACO 2017 FEB Platinum mincross 可持久化线段树

时间:2024-08-31 17:05:44

  题意

    上下有两个位置分别对应的序列A、B,长度为n,两序列为n的一个排列。当Ai == Bj时,上下会连一条边。你可以选择序列A或者序列B进行旋转任意K步,如 3 4 1 5 2 旋转两步为 5 2 3 4 1。求旋转后最小的相交的线段的对数。

  很暴力的就做了这一题,当选择A进行旋转时,A序列翻倍,然后建一棵主席树,记录点Bi的度数,为了更新用(其实可以O(1)更新),然后长度为n的区间扫一遍。

  B亦同。

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream> using namespace std; typedef long long LL;
const int maxn = *;
int n, a[maxn], b[maxn], to[maxn];
struct Tree
{
int sum[maxn*], ls[maxn*], rs[maxn*], cnt;
Tree()
{
cnt = ;
}
void pushup(int rt)
{
sum[rt] = sum[ls[rt]]+sum[rs[rt]];
}
void update(int las_rt, int rt, int l, int r, int p, int d)
{
if (l == r)
{
sum[rt] = sum[las_rt]+d;
return ;
}
int mid = (l+r)>>;
if (p <= mid)
{
ls[rt] = ++cnt, rs[rt] = rs[las_rt];
update(ls[las_rt], ls[rt], l, mid, p, d);
}
else
{
ls[rt] = ls[las_rt], rs[rt] = ++cnt;
update(rs[las_rt], rs[rt], mid+, r, p, d);
}
pushup(rt);
}
int query(int rt_1, int rt_2, int l, int r, int L, int R)
{
if (L <= l && r <= R)
return sum[rt_2]-sum[rt_1];
int mid = (l+r)>>, ret = ;
if (L <= mid)
ret += query(ls[rt_1], ls[rt_2], l, mid, L, R);
if (R > mid)
ret += query(rs[rt_1], rs[rt_2], mid+, r, L, R);
return ret;
}
}T1, T2;
int root1[maxn], root2[maxn]; int main()
{
freopen("mincross.in", "r", stdin);
freopen("mincross.out", "w", stdout);
scanf("%d", &n);
for (int i = ; i <= n; ++i)
scanf("%d", &a[i]), a[n+i] = a[i];
for (int i = ; i <= n; ++i)
scanf("%d", &b[i]), b[n+i] = b[i];
//part 1
for (int i = ; i <= n; ++i)
to[b[i]] = i;
root1[] = ++T1.cnt;
T1.update(, root1[], , n, to[a[]], );
for (int i = ; i <= *n; ++i)
{
root1[i] = ++T1.cnt;
T1.update(root1[i-], root1[i], , n, to[a[i]], );
}
LL now_sum = , ans;
for (int i = ; i <= n; ++i)
if (to[a[i]]+ <= n)
now_sum += T1.query(, root1[i], , n, to[a[i]]+, n);
ans = now_sum;
for (int i = n+; i <= *n; ++i)
{
int temp = ;
if (to[a[i]]- >= )
temp = T1.query(root1[i-n], root1[i-], , n, , to[a[i]]-);
now_sum -= temp, now_sum += (n-temp-);
ans = min(ans, now_sum);
}
//part 2
for (int i = ; i <= n; ++i)
to[a[i]] = i;
root2[] = ++T2.cnt;
T2.update(, root2[], , n, to[b[]], );
for (int i = ; i <= *n; ++i)
{
root2[i] = ++T2.cnt;
T2.update(root2[i-], root2[i], , n, to[b[i]], );
}
now_sum = ;
for (int i = ; i <= n; ++i)
if (to[b[i]]+ <= n)
now_sum += T2.query(, root2[i], , n, to[b[i]]+, n);
for (int i = n+; i <= *n; ++i)
{
int temp = ;
if (to[b[i]]- >= )
temp = T2.query(root2[i-n], root2[i-], , n, , to[b[i]]-);
now_sum -= temp, now_sum += (n-temp-);
ans = min(ans, now_sum);
}
cout <<ans <<endl;
return ;
}