Group
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 17 Accepted Submission(s): 5
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
2013 Multi-University Training Contest 4
Recommend zhuyuanchen520
把查询区间按照左端点排序。
然后逐渐从左边删除数,看对后面的影响。
树状数组实现单点更新和求和
/* * Author:kuangbin * 1007.cpp */ #include <stdio.h> #include <algorithm> #include <string.h> #include <iostream> #include <map> #include <vector> #include <queue> #include <set> #include <string> #include <math.h> using namespace std; const int MAXN = 100010; int n; int lowbit(int x) { return x&(-x); } int c[MAXN]; void add(int i,int val) { while(i <= n) { c[i] += val; i += lowbit(i); } } int sum(int i) { int s = 0; while(i > 0) { s += c[i]; i -= lowbit(i); } return s; } int a[MAXN]; int num[MAXN]; int ans[MAXN]; struct Node { int l,r; int index; }node[MAXN]; bool cmp(Node a,Node b) { return a.l < b.l; } int main() { //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int m; int T; scanf("%d",&T); while(T--) { scanf("%d%d",&n,&m); memset(c,0,sizeof(c)); for(int i = 1;i <= n;i++) { scanf("%d",&a[i]); num[a[i]]=i; } num[0] = n+10; num[n+1] = n+10; for(int i = 1;i <= n;i++) { if(i < num[a[i]-1] && i < num[a[i]+1]) add(i,1); else if(i > num[a[i]-1] && i > num[a[i]+1]) add(i,-1); } for(int i = 0;i < m;i++) { scanf("%d%d",&node[i].l,&node[i].r); node[i].index = i; } sort(node,node+m,cmp); int i = 1; int j = 0; while(j < m) { while(i <= n && i < node[j].l) { if(i > num[a[i]-1] && i > num[a[i]+1]) add(i,-1); else if(i < num[a[i]-1] && i < num[a[i]+1]) { int Min = min(num[a[i]-1],num[a[i]+1]); int Max = max(num[a[i]-1],num[a[i]+1]); add(i,-1); add(Min,1); add(Max,1); } else if(i < num[a[i]-1]) { add(i,-1); add(num[a[i]-1],1); } else { add(i,-1); add(num[a[i]+1],1); } i++; } while( j < m && node[j].l <= i) { ans[node[j].index]= sum(node[j].r); j++; } } for(int i = 0;i < m;i++) printf("%d\n",ans[i]); } return 0; }