codeforces 220 E. Little Elephant and Inversions (树状数组+尺取)

题目链接

题意:

how many pairs of integers l and r are there, such that 1 ≤ l < rn and sequence b = _a_1_a_2... a__l__a__r__a__r + 1... a__n has no more than k inversions.

我花了两个小时才看懂题。。。。一直没懂b数列中a[l]和a[r]怎么就挨着了。。。

其实意思是。。。只保留a数列中1..l和r..n的。。。构成b数列。。。然后b数列的逆序对数小于等于k.问这样的l,r的对数。

思路:尺取+树状数组。

枚举l,每次找到最小的满足题意的r,对答案的贡献是n-r+1,然后用两个树状数组,分别维护增加或者减少一个树的时候,前半段和后半段对逆序数的影响。

 1/* ***********************************************
 2Author :111qqz
 3Created Time :Wed 14 Sep 2016 04:23:06 PM CST
 4File Name :code/cf/problem/220E.cpp
 5************************************************ */
 6#include <cstdio>
 7#include <cstring>
 8#include <iostream>
 9#include <algorithm>
10#include <vector>
11#include <queue>
12#include <set>
13#include <map>
14#include <string>
15#include <cmath>
16#include <cstdlib>
17#include <ctime>
18#define fst first
19#define sec second
20#define lson l,m,rt<<1
21#define rson m+1,r,rt<<1|1
22#define ms(a,x) memset(a,x,sizeof(a))
23typedef long long LL;
24#define pi pair < int ,int >
25#define MP make_pair
26using namespace std;
27const double eps = 1E-8;
28const int dx4[4]={1,0,0,-1};
29const int dy4[4]={0,-1,1,0};
30const int inf = 0x3f3f3f3f;
31const int N=2E5+7;
32int tree[2][N];
33int a[N],p[N];
34int n;
35LL k;
36int lowbit( int x)
37{
38    return x&(-x);
39}
40void update (int o, int x,int delta)
41{
42    if (!o) x = n-x+1;
43    for ( int i = x; i  <= n ; i+=lowbit(i))  tree[o][i]+=delta;
44}
45int Hash( int x)
46{
47    return lower_bound(p+1,p+n+1,x)-p;
48}
49int Sum(int o, int x)
50{
51    if (!o) x = n-x+1;
52    int res = 0 ;
53    for ( int i = x; i >= 1 ; i-=lowbit(i)) res+=tree[o][i];
54    return res;
55}
56int main()
57{
58	#ifndef  ONLINE_JUDGE 
59	freopen("code/in.txt","r",stdin);
60  #endif
61	cin>>n>>k;
62	for ( int i = 1 ;i <= n ; i++) scanf("%d",a+i),p[i] = a[i];
63	sort(p+1,p+n+1);
64	LL total = 0;
65	for ( int i = n ; i >=1 ; i--)  //初始,l,r在同一位置,表示b就是a的全部,因此逆序对数就是整个数列的逆序对数,所以要先算一遍整体的逆序对数。
66	{
67	    int x = Hash(a[i]);
68	    a[i] = x;
69	    total +=Sum(1,a[i]-1);
70	    update(1,a[i],1);
71	}
72	int r = 1;
73	LL ans = 0;
74	for ( int l = 1 ; l <= n ; l++)
75	{
76	//    printf("tot:%lld ",total);
77	    total +=Sum(0,a[l]+1)+Sum(1,a[l]-1);//l和r在第一次之后就不会相邻了,那么增加一个l,分两段考虑它对逆序数的影响。
78	 //   printf(" tot2:%lld ",total);
79	    update(0,a[l],1);//维护逆序的bit
80	    while ((r<=l||total>k)&&r<=n)
81	    {
82		total-=Sum(0,a[r]+1)+Sum(1,a[r]-1);//从b数列中减去了之前的a[r],前后两段考虑对逆序对的影响。
83		update(1,a[r],-1);//在正向的bit中撤销a[r],因为a[r]已经不在b中了,不然会影响a[r]后面的数计算前半段的逆序数的影响。
84		r++;
85	    }
86	    ans+=n-r+1;//每次找到满足的最小的r,r到n一共由n-r+1个元素,这些都是满足的,因为序列中元素的个数减少,逆序对一定是非增加的。
87	  //  printf("l:%d r:%d ans: %lld total:%lld\n",l,r,ans,total);
88	}
89	cout<<ans<<endl;
90  #ifndef ONLINE_JUDGE  
91  fclose(stdin);
92  #endif
93    return 0;
94}