USACO-Section 1.4 Arithmetic Progressions

11 篇文章 0 订阅

题意:
找所有满足以下条件的等差数列,先按公差排序,再按首项排序。
(1)每项都是两个数平方和
(2)长度为n

题解:
首先找到所有(两平方数和)并排序;
然后遍历,外循环是首项,内循环是第二项,得到公差,根据此公差在后面的数中若能再找到n-2个数 ,则满足条件。

Question:结构体定义放在全局变量后面竟然超时了; 放得靠前就不会???

/*
ID:jsntrdy1
PROG:ariprog 
LANG: C++
*/
#include<cstdio>
#include<iostream>
#include<cstring>
#include<fstream>
#include<algorithm>
using namespace std;
const int N=150000;//250*250*2
struct node{
    int a1;
    int d;
}w[N];
int pq[N];//记录平方数和是否存在
int t[N];//平方数和

int n,m;
int ans;//满足条件的等差数列的个数
int len;//平方数和 的个数

bool cmp(node a,node b)
{
    return a.d<b.d||(a.d==b.d&&a.a1<b.a1);
}

int main()
{
    ifstream fin("ariprog.in");
    ofstream fout("ariprog.out");

    fin>>n>>m;
    for(int p=0;p<=m;p++)
    {
        for(int q=p;q<=m;q++)
        {
            pq[p*p+q*q]=1;
        }
    }

    for(int i=0;i<N;i++)
    {
        if(pq[i])
         t[len++]=i;

    }

    for(int i=0;i<len;i++)
    {
        for(int j=i+1;j<len;j++)
        {
            int dd=t[j]-t[i];
            int k;
            for(k=2;k<n;k++)
            {
                if(!pq[t[i]+dd*k])
                  break;
            } 
            if(k==n)
            {
                w[ans].a1=t[i];
                w[ans].d=dd;
                ans++;
            }
        }
    }
    if (ans){

    sort(w,w+ans,cmp);
    for(int i=0;i<ans;i++)
      fout<<w[i].a1<<' '<<w[i].d<<endl;
    }
    else
      fout<<"NONE"<<endl;
    fin.close();
    fout.close();  
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值