hdu 4638 Group(离线+树状数组)
Group
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 546 Accepted Submission(s): 299
Problem Description
There are n men ,every man has an ID(1..n).their ID is unique. Whose ID is i and i-1 are friends, Whose ID is i and i+1 are friends. These n men stand in line. Now we select an interval of men to make some group. K men in a group can create K*K value. The value of an interval is sum of these value of groups. The people of same group's id must be continuous. Now we chose an interval of men and want to know there should be how many groups so the value of interval is max.
Input
First line is T indicate the case number. For each case first line is n, m(1<=n ,m<=100000) indicate there are n men and m query. Then a line have n number indicate the ID of men from left to right. Next m line each line has two number L,R(1<=L<=R<=n),mean we want to know the answer of [L,R].
Output
For every query output a number indicate there should be how many group so that the sum of value is max.
Sample Input
1
5 2
3 1 2 5 4
1 5
2 4
Sample Output
1
2
Source
Recommend
zhuyuanchen520
队友的思路!!
先按区间右端点r排升序!!
下面是操作:(若之前有相邻的,就把那位上减1,相当于把之前的组归到当前的组!!!)
如 3 1 2 5 4
3 in: 1
1 in: 1 1
2 in: 1-1=0 1-1=0 1
5 in: 0 0 1 1
4 in: 0-1=-1 0 1 1-1=0 1
然后再区间求和即可!!!
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #include<string.h> 3 #include<queue> 4 #include<vector> 5 #include<algorithm> 6 using namespace std; 7 typedef long long ll; 8 #define lowbit(x) (x&(-x)) 9 const int N=100010; 10 int C[N],n; 11 12 void add(int x,int inc){ 13 while(x<=n){ 14 C[x]+=inc; 15 x+=lowbit(x); 16 } 17 } 18 int sum(int x){ 19 int res=0; 20 while(x){ 21 res+=C[x]; 22 x-=lowbit(x); 23 } 24 return res; 25 } 26 27 int a[N]; 28 struct node 29 { 30 int l,r,id,ans; 31 }query[N]; 32 struct ppp 33 { 34 int x[5],cc; 35 void init() 36 { 37 memset(x,0,sizeof(x)); 38 cc=0; 39 } 40 }b[N];//b[i]用来储存与i相邻的数的下标且 这个相邻的数在i之前!! 41 bool cmpR(node a,node b) 42 { 43 return a.r<b.r; 44 } 45 bool cmpID(node a,node b) 46 { 47 return a.id<b.id; 48 } 49 int main() 50 { 51 int i,m,T; 52 scanf("%d",&T); 53 while(T--) 54 { 55 56 memset(C,0,sizeof(C)); 57 for(i=1;i<N;i++)b[i].init(); 58 scanf("%d%d",&n,&m); 59 for(i=1;i<=n;i++)scanf("%d",&a[i]); 60 for(i=1;i<=m;i++)scanf("%d%d",&query[i].l,&query[i].r),query[i].id=i; 61 sort(query+1,query+m+1,cmpR); 62 int cnt=1; 63 for(i=1;i<=n;i++) 64 { 65 int tmp=a[i]; 66 if(b[tmp].x[1])add(b[tmp].x[1],-1);//将之前出现过与之相邻的数减1,单点更新!! 67 if(b[tmp].x[2])add(b[tmp].x[2],-1); 68 if(tmp-1>=1) 69 { 70 b[tmp-1].x[++b[tmp-1].cc]=i; 71 } 72 if(tmp+1<=n) 73 { 74 b[tmp+1].x[++b[tmp+1].cc]=i; 75 } 76 add(i,1); 77 while(i==query[cnt].r) 78 { 79 query[cnt].ans=sum(query[cnt].r)-sum(query[cnt].l-1); 80 cnt++; 81 } 82 } 83 sort(query+1,query+m+1,cmpID); 84 for(i=1;i<=m;i++)printf("%d\n",query[i].ans); 85 } 86 }