USACO 1.4 等差数列

题目:https://www.luogu.org/problemnew/show/P1214

枚举前两项,计算即可

但是得有一个小优化:如果最后一项大于最大值,就直接退出

代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
inline int read()
{
  int ans = 0,op = 1;
  char ch = getchar();
  while(ch < '0' || ch > '9')
    {
      if(ch == '-') op = -1;
      ch = getchar();
    }
  while(ch >= '0' && ch <= '9')
    {
      (ans *= 10) += ch - '0';
      ch = getchar();
    }
  return ans * op;
}
int a[250 * 250 * 4];
bool ok[250 * 250 * 4];
int n,m;
int tot = 0;
int ans = 0;
struct node
{
  int a,b;
}p[100001];
  bool cmp(const node &k1,const node &k2)
  {
    return k1.b < k2.b || (k1.b == k2.b && k1.a < k2.a);
  }
int main()
{
  bool o = 0;
  int ans = 0;
  n = read(),m = read();
  for(int i = 0;i <= m;i++)
    for(int j = 0;j <= m;j++)
      if(ok[i * i + j * j] == 0) a[++tot] = i * i + j * j,ok[i * i + j * j] = 1;
  sort(a + 1,a + 1 + tot);
  for(int i = 1;i<= tot;i++)
    for(int j = i + 1;j <= tot;j++)
      {
    int b = a[j] - a[i];
    //if(a[j] - (n - 2) * b < 0) break;
    if(a[j] + (n - 2) * b > 2 * m * m) break;
    bool flag = 1;
    for(int k = 1;k <= n - 1;k++)
      if(ok[a[i] + b * k] == 0) {flag = 0; break; }
    if(flag) p[++ans].a = a[i],p[ans].b = b,o = 1;
      }
  if(o == 0) {printf("NONE"); return 0;}
  sort(p + 1,p + 1 + ans,cmp);
  for(int i = 1;i <= ans;i++) printf("%d %d\n",p[i].a,p[i].b);
}

猜你喜欢

转载自www.cnblogs.com/LM-LBG/p/9973286.html