您的位置:首页 > 移动开发

[CodeForces 602B]Approximating a Constant Range[构造]

2016-02-22 19:45 513 查看
题目链接:[CodeForces 602B]Approximating a Constant Range[构造]
题意分析:

给出一个数列,各项绝对值之差不超过1,求最大的区间长度,使得区间内最大的数减去最小的数差不超过1。

解题思路:

用p[i]记录数字i出现的最大位置,那么到达数字x时,我们只需要对x-1和x+1的最大位置进行判断,就能确定如何计算区间长度。下面仅讨论其中一种情况:

假设p[x-1]>p[x+1],那么此时组成区间的数应该为x和x-1,这时的区间长度为i - max(p[x + 1], p[x - 2])。这里max里面出现x-2是因为,有可能在x+1之后出现x-2的情况,但是绝不可能出现x+2因为从x+2到x-1必然会经历x+1此时的p[x+1]就被更新了,和原来的定义不符合。

个人感受:

机智啊机智,学习学习Orz

具体代码如下:

#include<algorithm>
#include<cctype>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<sstream>
#include<stack>
#include<string>
#define lowbit(x) (x & (-x))
#define root 1, n, 1
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 1
#define ll long long
#define pr(x) cout << #x << " = " << (x) << '\n';
using namespace std;

const int INF = 0x7f7f7f7f;
const int MAXN = 1e5 + 111;

int p[MAXN];

int main()
{
int n, x, ans = 0;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &x);
if (p[x - 1] > p[x + 1]) ans = max(ans, i - max(p[x - 2], p[x + 1]));
else ans = max(ans, i - max(p[x - 1], p[x + 2]));
p[x] = i;
}
printf("%d\n", ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: