码迷,mamicode.com
首页 > 其他好文 > 详细

【bzoj3289】Mato的文件管理

时间:2015-09-06 06:22:00      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

3289: Mato的文件管理

Time Limit: 40 Sec  Memory Limit: 128 MB
Submit: 1056  Solved: 464
[Submit][Status][Discuss]

Description

Mato同学从各路神犇以各种方式(你们懂的)收集了许多资料,这些资料一共有n份,每份有一个大小和一个编号。为了防止他人偷拷,这些资料都是加密过的,只能用Mato自己写的程序才能访问。Mato每天随机选一个区间[l,r],他今天就看编号在此区间内的这些资料。Mato有一个习惯,他总是从文件大小从小到大看资料。他先把要看的文件按编号顺序依次拷贝出来,再用他写的排序程序给文件大小排序。排序程序可以在1单位时间内交换2个相邻的文件(因为加密需要,不能随机访问)。Mato想要使文件交换次数最小,你能告诉他每天需要交换多少次吗?

Input

第一行一个正整数n,表示Mato的资料份数。
第二行由空格隔开的n个正整数,第i个表示编号为i的资料的大小。
第三行一个正整数q,表示Mato会看几天资料。
之后q行每行两个正整数l、r,表示Mato这天看[l,r]区间的文件。

Output

q行,每行一个正整数,表示Mato这天需要交换的次数。

Sample Input

4
1 4 2 3
2
1 2
2 4

Sample Output

0
2


HINT

Hint

n,q <= 50000

样例解释:第一天,Mato不需要交换

第二天,Mato可以把2号交换2次移到最后。

Source

 

By taorunz

 


糖教主的题ORZ: 

 思路都是莫对,现在发现莫对模板很好用,

求区间逆序数多少,转移难推2333

其他一样 

 

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<string.h>
 4 #include<math.h>
 5 #include<algorithm>
 6 #include<queue>
 7 #include<vector>
 8 #include<stdlib.h>
 9 
10 #define inf 0x3f3f3f
11 #define N 1234567
12 
13 using namespace std;
14 
15 int a[N],pos[N],block,b[N];
16 int n,m,k;
17 int f[N];
18 struct node
19 {
20     int l,r,id,ans;
21 }q[N];
22 
23 int cmp(node a,node b)
24 {
25     if (pos[a.l]==pos[b.l]) return a.r<b.r;
26     return pos[a.l]<pos[b.l];
27 }
28 
29 void add(int x,int val)
30 {
31     for (int i=x;i<=n;i+=i&-i)
32     f[i]+=val;
33 }
34 
35 int query(int x)
36 {
37     int s=0;
38     for (int i=x;i;i-=i&-i)
39     s+=f[i];
40     return s;
41 }
42 
43 int cmpid(node a,node b)
44 {
45     return a.id<b.id;
46 }
47 
48 
49 void solve()
50 {
51     int l=1,r=0;
52     int ans=0;
53     for (int i=1;i<=m;i++)
54     {
55         while (l<q[i].l)
56         add(a[l],-1),ans-=query(a[l]-1),l++;//减去a[l]产生的影响
57         while (l>q[i].l)
58         l--,add(a[l],1),ans+=query(a[l]-1);//加上a[l]的infection
59         while (r>q[i].r)
60         add(a[r],-1),ans-=r-l-query(a[r]),r--;//d the infection of a[r] ,note r-l
61         while (r<q[i].r)
62         r++,add(a[r],1),ans+=r-l+1-query(a[r]);//add the infection of a[r]
63         
64         q[i].ans=ans;
65     }
66 }
67 
68 int main()
69 {
70     scanf("%d",&n);
71     for (int i=1;i<=n;i++) scanf("%d",&a[i]),b[i]=a[i];
72     scanf("%d",&m);
73     block=sqrt(n);
74     
75     for (int i=1;i<=n;i++)
76     pos[i]=(i-1)/block+1;
77     sort(b+1,b+n+1);
78     for (int i=1;i<=n;i++) a[i]=lower_bound(b+1,b+n+1,a[i])-b;
79 
80     for (int i=1;i<=m;i++)
81     scanf("%d%d",&q[i].l,&q[i].r),q[i].id=i;
82 
83     sort(q+1,q+m+1,cmp);
84     solve();
85     sort(q+1,q+m+1,cmpid);
86     for (int i=1;i<=m;i++)
87     printf("%d\n",q[i].ans);

88 } 

 

【bzoj3289】Mato的文件管理

标签:

原文地址:http://www.cnblogs.com/forgot93/p/4784320.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!