zoukankan      html  css  js  c++  java
  • A Simple Problem

    Description

           在一个由N个整数组成的数列中,最多能找到多少个位置连续的整数且其中的最大值与最小值之差不超过K呢?

    Input

           输入包含若干组数据。每组数据的第一行有2个正整数,N(1<=N<=10^6),K(0<=K<=10^6),其中N、K的含义同上,接下来一行一共有N个32位有符号整数(32-bit signed integer),依次描绘了这个数列中各个整数的值。

    Output

           对于每组数据,输出一个正整数,表示在这个数列中最多能找到多少个位置连续的整数且其中的最大值与最小值之差不超过K。

    Sample Input

    4 2
    3 1 5 2
    
    3 2
    3 1 2
    

    Sample Output

    2
    3
    

    Hint

          由于数据量较大,建议C++选手选用scanf来读取数据。


    Submit Page

    #include<iostream>
    #include<cstdio>
    #include<cmath>
    #include<cstring>
    using namespace std;
    const int Min=0x3f3f3f3f;
    const long long MIn=0x3f3f3f3f3f3f3f3f;
    const int maxn=1e6+10;
    int a[maxn],q1[maxn],q2[maxn],r1,r2,f1,f2;
    
    inline int work(int x,int y,int k)
    {
    	long long cx,cy,ck;
    	cx=x,cy=y,ck=k;
    	if(abs(cx-cy)<=k) return 1;
    	else return 0;
    }
    
    int main()
    {
    	int n,k,pos1,pos2,ans;
    	while(~scanf("%d%d",&n,&k))
    	{
    		ans=1;
    		for(int i=1;i<=n;i++) scanf("%d",a+i);
    		r1=r2=1;
    		f1=f2=0;
    		q1[0]=q2[0]=1;
    		pos1=pos2=1;
    		while(pos2<n)
    		{
    			while(pos2<n && work(a[q1[f1]],a[q2[f2]],k))
    			{
    				pos2++;
    				while(r1>f1 && a[q1[r1-1]]>=a[pos2]) r1--; 
    				q1[r1++]=pos2;
    				while(r2>f2 && a[q2[r2-1]]<=a[pos2]) r2--;
    				q2[r2++]=pos2;
    			}
    			int len=pos2-pos1;
    			if(pos2==n && work(a[q1[f1]],a[q2[f2]],k)) len++;
    			ans=max(ans,len);
    			if(a[q1[f1]]==a[pos2])
    			{
    				while(f1<r1 && !work(a[q1[f1]],a[q2[f2]],k)) f2++;
    				pos1=q2[f2-1]+1;
    			}
    			else if(a[q2[f2]]==a[pos2])
    			{
    				while(f2<r2 && !work(a[q2[f2]],a[q1[f1]],k)) f1++;
    				pos1=q1[f1-1]+1;
    			}
    		}
    		printf("%d
    ",ans);
    	}
    	
    	
    	return 0;
     } 
    /**********************************************************************
    	Problem: 1170
    	User: song_hai_lei
    	Language: C++
    	Result: AC
    	Time:260 ms
    	Memory:13740 kb
    **********************************************************************/
    



  • 相关阅读:
    struts1与struts2的防止表单重复提交
    JSTL 笔记
    fiddler的columns添加HTTPMethod
    兼容性测试技巧
    测试基础知识总结
    测试用例的书写方式及测试模板大全【转】
    软件测试的方法分类
    解决vue不支持promise语法问题
    vue-router 导航守卫
    e.target与事件委托简例【转】
  • 原文地址:https://www.cnblogs.com/csushl/p/9386555.html
Copyright © 2011-2022 走看看