HDU 5328 Problem Killer
题意:给一段序列,求连续的子序列中最长的等差数列或者等比数列的长度。
解法:O(n)的扫两遍一次判等差一次判等比就好了。
代码:
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<math.h>
#include<limits.h>
#include<time.h>
#include<stdlib.h>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#define LL long long
using namespace std;
int a[1000005];
bool equal(int a1, int a2, int b1, int b2)
{
int r1 = __gcd(a1, a2), r2 = __gcd(b1, b2);
a1 /= r1;
a2 /= r1;
b1 /= r2;
b2 /= r2;
return a1 == b1 && a2 == b2;
}
int main()
{
int T;
while(~scanf("%d", &T))
{
while(T--)
{
int n;
scanf("%d", &n);
for(int i = 1; i <= n; i++)
scanf("%d", &a[i]);
int ans = 1;
int flag = 0;
int res = 2;
for(int i = 2; i <= n; i++)
{
if(!flag)
{
res = 2;
flag = 1;
ans = max(res, ans);
}
else
{
if(a[i] - a[i - 1] == a[i - 1] - a[i - 2])
{
res++;
ans = max(ans, res);
}
else
{
flag = 0;
i--;
}
}
}
flag = 0;
res = 2;
for(int i = 2; i <= n; i++)
{
if(!flag)
{
res = 2;
flag = 1;
ans = max(res, ans);
}
else
{
if(equal(a[i], a[i - 1], a[i - 1], a[i - 2]))
{
res++;
ans = max(ans, res);
}
else
{
flag = 0;
i--;
}
}
}
printf("%d\n", ans);
}
}
return 0;
}

浙公网安备 33010602011771号