Description
排排坐,吃果果,生果甜嗦嗦,大家笑呵呵。你一个,我一个,大的分给你,小的留给我,吃完果果唱支歌,大家乐和和。红星幼儿园的小朋友们排起了长长地队伍,准备吃果果。不过因为小朋友们的身高有所区别,排成的队伍高低错乱,极不美观。设第i个小朋友的身高为hi,我们定义一个序列的杂乱程度为:满足ihj的(i,j)数量。幼儿园阿姨每次会选出两个小朋友,交换他们的位置,请你帮忙计算出每次交换后,序列的杂乱程度。为方便幼儿园阿姨统计,在未进行任何交换操作时,你也应该输出该序列的杂乱程度。
Input
第一行为一个正整数n,表示小朋友的数量;第二行包含n个由空格分隔的正整数h1,h2,…,hn,依次表示初始队列中小朋友的身高;第三行为一个正整数m,表示交换操作的次数;以下m行每行包含两个正整数ai和bi¬,表示交换位置ai与位置bi的小朋友。
Output
输出文件共m行,第i行一个正整数表示交换操作i结束后,序列的杂乱程度。
Sample Input
【样例输入】
3
130 150 140
2
2 3
1 3
Sample Output
1
0
3
【样例说明】
未进行任何操作时,(2,3)满足条件;
操作1结束后,序列为130 140 150,不存在满足ihj的(i,j)对;
操作2结束后,序列为150 140 130,(1,2),(1,3),(2,3)共3对满足条件的(i,j)。
【数据规模和约定】
对于100%的数据,1≤m≤2*103,1≤n≤2*104,1≤hi≤109,ai≠bi,1≤ai,bi≤n。
如果不会用树状数组求逆序对 戳这里
题意:求区间逆序对个数
solution:分块+树状数组
/**************************************************************
Problem: 2141
User: Venishel
Language: C++
Result: Accepted
Time:492 ms
Memory:17400 kb
****************************************************************/
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define M 20200
using namespace std;
int n, m, ans, tot, block, a[M];
pair<int,int>b[M];
int pre[M],cnt[200][M];
inline void swap(int &x, int &y) {
x^=y;
y^=x;
x^=y;
}
void up( int t[], int x){
for( ; x <= n; x += x&-x ) ++t[x];
}
void down(int t[],int x){
for(; x <= n; x += x&-x ) --t[x];
}
int query(int t[],int x){
int ret = 0;
for(; x; x -= x&-x )
ret += t[x];
return ret;
}
int main(){
register int i,j,x,y;
scanf( "%d", &n );
for( i = 1; i <= n; i++)
scanf( "%d", &b[i].first), b[i].second=i;
sort( b+1, b+n+1 );
for( i = 1; i <= n; i++){
if ( b[i].first != b[i-1].first) ++tot;
a[ b[i].second ] = tot;
}
for ( i = n; i; i--)
ans += query( pre, a[i] - 1 ), up( pre, a[i] );
block = sqrt(n);
for( i = 1; i <= n; i++)
up( cnt[(i-1)/block ], a[i]);
printf( "%d\n", ans);
scanf( "%d", &m );
for( i = 1; i <= m; i++ ){
scanf( "%d%d", &x, &y);
if( x > y ) swap( x, y);
int b1= ( x - 1 ) / block + 1;
int b2= ( y - 1 ) / block - 1;
if( b1 <= b2 ){
for( j = b1; j <= b2; j++){
ans -= query( cnt[j], a[x]-1);
ans += query( cnt[j], n) - query( cnt[j], a[x]);
ans += query( cnt[j], a[y]-1 );
ans -= query( cnt[j], n) - query( cnt[j], a[y]);
}
for( j = x + 1; j <= b1 * block; j++){
if( a[j] < a[x]) --ans;
if( a[j] > a[x]) ++ans;
if( a[j] < a[y]) ++ans;
if( a[j] > a[y]) --ans;
}
for( j = ( b2 + 1 ) * block + 1; j < y; j++)
{
if( a[j] < a[x]) --ans;
if( a[j] > a[x]) ++ans;
if( a[j] < a[y]) ++ans;
if( a[j] > a[y]) --ans;
}
}
else
{
for( j = x+1; j <= y-1; j++)
{
if( a[j] < a[x]) --ans;
if( a[j] > a[x]) ++ans;
if( a[j] < a[y]) ++ans;
if( a[j] > a[y]) --ans;
}
}
if( a[x] < a[y] ) ++ans;
else if( a[x] > a[y] ) --ans;
printf( "%d\n", ans);
down( cnt[(x-1)/block], a[x] );
down( cnt[(y-1)/block], a[y] );
swap( a[x], a[y]);
up( cnt[(x-1)/block], a[x]);
up( cnt[(y-1)/block], a[y]);
}
}