gpt4 book ai didi

c++ - 算法:最长近似间隔

转载 作者:行者123 更新时间:2023-12-01 14:49:45 24 4
gpt4 key购买 nike

我正在尝试解决这个问题:

When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it?

You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1.

A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1.

Find the length of the longest almost constant range.

Input The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points.

The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000).

Output Print a single number — the maximum length of an almost constant range of the given sequence.



https://codeforces.com/problemset/problem/602/B

我在这里看到了一个解决方案,但我不明白算法 - 特别是循环的主体。我熟悉 C++ 语法,我明白发生了什么。我只是不明白为什么算法有效。
#include<cstdio>
#include<algorithm>
using namespace std;
int a[1000005];
int main()
{
int n,ans = 2,x;
scanf("%d",&n);
for(int i = 1; i <= n; i++)
{

scanf("%d",&x);
a[x] = i;
if(a[x-1] > a[x+1])
ans = max(ans,i-max(a[x+1],a[x-2]));
else
ans = max(ans,i-max(a[x+2],a[x-1]));
}
printf("%d\n",ans);
return 0;
}

有人可以向我解释一下吗?

最佳答案

数组 a代表值 x 的最后一个位置.

现在让我们计算每个位置的左边界(值为 x ),如果 a[x - 1]更接近a[x]比较 a[x + 1] ,表示将打破几乎不变规则的位置在a[x + 1] (因为中间有 x - 1)或 a[x - 2] (因为中间有一个 x - 1)。

反之亦然。

关于c++ - 算法:最长近似间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58716986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com