poj 3368 Frequent values (暴力+rmq,分类讨论)

poj 3368 题目链接

题意:给出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应该过不了吧。。。但是所有题解都是这么写的。。。不是很懂。。。所谓的面向数据编程?

不过还是有启示的:分类讨论的思想。一道题未必用一种算法解。如果因为一小部分导致某算法不能用的话,不妨暴力搞之然后再用这个算法。

  1/* ***********************************************
  2Author :111qqz
  3Created Time :2016年05月18日 星期三 13时44分47秒
  4File Name :code/poj/3368.cpp
  5************************************************ */
  6
  7#include <cstdio>
  8#include <cstring>
  9#include <iostream>
 10#include <algorithm>
 11#include <vector>
 12#include <queue>
 13#include <set>
 14#include <map>
 15#include <string>
 16#include <cmath>
 17#include <cstdlib>
 18#include <ctime>
 19#define fst first
 20#define sec second
 21#define lson l,m,rt<<1
 22#define rson m+1,r,rt<<1|1
 23#define ms(a,x) memset(a,x,sizeof(a))
 24typedef long long LL;
 25#define pi pair < int ,int >
 26#define MP make_pair
 27
 28using namespace std;
 29const double eps = 1E-8;
 30const int dx4[4]={1,0,0,-1};
 31const int dy4[4]={0,-1,1,0};
 32const int inf = 0x3f3f3f3f;
 33const int N=1E5+7;
 34int n;
 35pi a[N];
 36int q;
 37int dp[N][20];
 38
 39void init_rmq()
 40{
 41    for ( int i =  1 ;i  <= n ; i++) dp[i][0] = a[i].sec;
 42
 43    for ( int j = 1  ; (1<<j)<= n ; j++)
 44	for ( int i = 1 ; i + (1<<j)-1 <= n ; i++)
 45	    dp[i][j] = max(dp[i][j-1],dp[i+(1<<(j-1))][j-1]);
 46}
 47
 48int rmq_max(int l,int r)
 49{
 50    if (l>r) return 0; //因为l+1可能大于b
 51    int k = 0  ;
 52    while (1<<(k+1)<=(r-l+1)) k++;
 53    return max(dp[l][k],dp[r-(1<<k)+1][k]);
 54
 55}
 56int main()
 57{
 58	#ifndef  ONLINE_JUDGE 
 59	freopen("code/in.txt","r",stdin);
 60  #endif
 61
 62	while (scanf("%d",&n)!=EOF)
 63	{
 64	    ms(dp,0);
 65	    ms(a,0);
 66
 67	    if (n==0) break;
 68	    scanf("%d",&q);
 69	    for ( int i = 1 ; i <= n ; i++)
 70	    {
 71		int x;
 72		scanf("%d",&x);
 73		a[i]=make_pair(x,1);
 74	    }
 75	    a[n+1].fst = inf;
 76
 77	    for ( int i = 2 ; i <= n ; i++)
 78	    {
 79		if (a[i].fst==a[i-1].fst)
 80		{
 81		    a[i].sec = a[i-1].sec+1;
 82		}
 83	    }
 84
 85//	    for ( int i = 1 ;i  <= n ; i++) cout<<a[i].fst<<" "<<a[i].sec<<endl;
 86
 87	    init_rmq();
 88	    while (q--)
 89	    {
 90		int l,r;
 91		scanf("%d %d",&l,&r);
 92		int tmp = l;
 93		while (tmp<r&&a[tmp].fst==a[tmp+1].fst) tmp++; //mdzz,最坏复杂度1E10啊。。。题解都是面向数据编程吗
 94		int ans = rmq_max(tmp+1,r);
 95//		cout<<"tmp-l:"<<tmp-l+1<<endl;
 96		ans = max(ans,tmp+1-l);
 97		printf("%d\n",ans);
 98	    }
 99
100	}
101
102  #ifndef ONLINE_JUDGE  
103  fclose(stdin);
104  #endif
105    return 0;
106}