poj 3368 Frequent values (暴力+rmq,分类讨论)
题意:给出n个非减的数a[i],求区间[l,r]中出现次数最多的数的出现的次数。
思路:由于数列非减,那么相等的数一定相邻。很容易系哪个到构造另一个数组f[i],表示从当前位置向左边延伸最多延伸几个相等的数。
f[i] = f[i-1] + 1 (iff a[i]==a[i-1])
然后查询的时候。
如果直接用ST算法查询rmq的话。。。
可能产生错误结果,原因是f[i]是从左边1到i这段连续区间里当前数出现的次数。
但是查询区间不一定是从1开始,所以查询区间内的第一段连续相等的数可能不完整。。。想了半天。。最后看了题解,发现是这部分暴力来搞。但是如果所有数列中所有数都相等,这样的复杂度就达到了o(1E10)?。。。2s应该过不了吧。。。但是所有题解都是这么写的。。。不是很懂。。。所谓的面向数据编程?
不过还是有启示的:分类讨论的思想。一道题未必用一种算法解。如果因为一小部分导致某算法不能用的话,不妨暴力搞之然后再用这个算法。
/* ***********************************************
Author :111qqz
Created Time :2016年05月18日 星期三 13时44分47秒
File Name :code/poj/3368.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <set>
8#include <map>
9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6const int N=1E5+7;
7int n;
8pi a[N];
9int q;
10int dp[N][20];
1void init_rmq()
2{
3 for ( int i = 1 ;i <= n ; i++) dp[i][0] = a[i].sec;
1 for ( int j = 1 ; (1<<j)<= n ; j++)
2 for ( int i = 1 ; i + (1<<j)-1 <= n ; i++)
3 dp[i][j] = max(dp[i][j-1],dp[i+(1<<(j-1))][j-1]);
4}
1int rmq_max(int l,int r)
2{
3 if (l>r) return 0; //因为l+1可能大于b
4 int k = 0 ;
5 while (1<<(k+1)<=(r-l+1)) k++;
6 return max(dp[l][k],dp[r-(1<<k)+1][k]);
1}
2int main()
3{
4 #ifndef ONLINE_JUDGE
5 freopen("code/in.txt","r",stdin);
6 #endif
1 while (scanf("%d",&n)!=EOF)
2 {
3 ms(dp,0);
4 ms(a,0);
1 if (n==0) break;
2 scanf("%d",&q);
3 for ( int i = 1 ; i <= n ; i++)
4 {
5 int x;
6 scanf("%d",&x);
7 a[i]=make_pair(x,1);
8 }
9 a[n+1].fst = inf;
1 for ( int i = 2 ; i <= n ; i++)
2 {
3 if (a[i].fst==a[i-1].fst)
4 {
5 a[i].sec = a[i-1].sec+1;
6 }
7 }
// for ( int i = 1 ;i <= n ; i++) cout<<a[i].fst<<" "<<a[i].sec<<endl;
1 init_rmq();
2 while (q--)
3 {
4 int l,r;
5 scanf("%d %d",&l,&r);
6 int tmp = l;
7 while (tmp<r&&a[tmp].fst==a[tmp+1].fst) tmp++; //mdzz,最坏复杂度1E10啊。。。题解都是面向数据编程吗
8 int ans = rmq_max(tmp+1,r);
9// cout<<"tmp-l:"<<tmp-l+1<<endl;
10 ans = max(ans,tmp+1-l);
11 printf("%d\n",ans);
12 }
}
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}