Address: frequent values
Theme and solution ideas: see the White Paper p198.
Code:
1 #include <stdio.h> 2 #include <string.h> 3 #include <math.h> 4 #include <algorithm> 5 #include <vector> 6 using namespace std; 7 const int M=100100; 8 int a[M]; 9 int val[M],cnt[M];10 int num[M],left[M],right[M];11 int d[M][20];12 int id;13 void RMQ_init(int A[])14 {15 int i,j;16 for(i=0; i<id; i++)17 d[i][0]=A[i];18 for(j=1; (1<<j)<=id; j++)19 for(i=0; i+(1<<j)-1<id; i++)20 d[i][j]=max(d[i][j-1],d[i+(1<<(j-1))][j-1]);21 }22 int RMQ(int L,int R)23 {24 int k=0;25 while((1<<(k+1))<=R-L+1)26 k++;27 return max(d[L][k],d[R-(1<<k)+1][k]);28 }29 int main()30 {31 int n;32 while(scanf("%d",&n)&&n)33 {34 int q;35 scanf("%d",&q);36 int i,j;37 id=0;38 scanf("%d",&a[1]);39 val[++id]=a[1];40 left[id]=1;41 int xu=1;42 num[1]=xu;43 for(i=2; i<=n; i++)44 {45 scanf("%d",&a[i]);46 if (a[i]!=a[i-1])47 {48 val[++id]=a[i];49 left[id]=i;50 right[id-1]=i-1;51 cnt[id-1]=i-left[id-1];52 xu++;53 }54 num[i]=xu;55 }56 right[id]=i-1;57 cnt[id]=i-left[id];58 RMQ_init(cnt);59 int xu1,xu2;60 int sum1=0,sum2=0,sum3=0,sum=0;61 while(q--)62 {63 int x,y;64 scanf("%d%d",&x,&y);65 xu1=num[x];66 xu2=num[y];67 if (xu1!=xu2)68 {69 sum1=right[xu1]-x+1;70 sum3=y-left[xu2]+1;71 sum=sum1;72 if (sum<sum3)73 sum=sum3;74 if (xu1+1<=xu2-1)75 {76 sum2=RMQ(xu1+1,xu2-1);77 if (sum<sum2)78 sum=sum2;79 }80 }81 else82 {83 sum=y-x+1;84 }85 printf("%d\n",sum);86 }87 }88 return 0;89 }90 /*91 10 392 -1 -1 1 1 1 1 3 10 10 1093 2 394 1 1095 5 1096 097 98 */
View code
Uva11235 (frequent values) (hdu1806)