码迷,mamicode.com
首页 > 其他好文 > 详细

USACO 1.4 Arithmetic Progressions

时间:2015-09-09 19:23:52      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

Arithmetic Progressions

An arithmetic progression is a sequence of the form a, a+b, a+2b, ..., a+nb where n=0,1,2,3,... . For this problem, a is a non-negative integer and b is a positive integer.

Write a program that finds all arithmetic progressions of length n in the set S of bisquares. The set of bisquares is defined as the set of all integers of the form p2 + q2 (where p and q are non-negative integers).

TIME LIMIT: 5 secs

PROGRAM NAME: ariprog

INPUT FORMAT

Line 1: N (3 <= N <= 25), the length of progressions for which to search
Line 2: M (1 <= M <= 250), an upper bound to limit the search to the bisquares with 0 <= p,q <= M.

SAMPLE INPUT (file ariprog.in)

5
7

OUTPUT FORMAT

If no sequence is found, a single line reading `NONE‘. Otherwise, output one or more lines, each with two integers: the first element in a found sequence and the difference between consecutive elements in the same sequence. The lines should be ordered with smallest-difference sequences first and smallest starting number within those sequences first.

There will be no more than 10,000 sequences.

SAMPLE OUTPUT (file ariprog.out)

1 4
37 4
2 8
29 8
1 12
5 12
13 12
17 12
5 20
2 24

题读了好长时间,代码码了20分钟,一遍过了,开心。
题意:一个长度为N的等差数列a+i*b,等差数列里的所有元素都必须是双平方数(即有p*p+q*q组成的数)。给了数列长度N,和p与q的取值范围(0<=p,q<=M)枚举出所有的a和b。
题解:我先预处理算出了所有的双平方数,然后枚举b和a,判断即可。代码才写了60行
ps:本人大三狗一枚,正在持续更新博客,文章里有任何问题,希望各位网友可以指出。若有疑问也可在评论区留言,我会尽快回复。希望能与各位网友互相学习,谢谢
/*
ID: cxq_xia1
PROG: ariprog
LANG: C++
*/

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
int N,M;
bool flag[125005];
bool check(int a,int b)
{
    int val;
    for(int i=0;i<N;i++)
    {
        val=a+i*b;
        if(!flag[val])
            return false;
    }
        return true;
}

int main()
{
    freopen("ariprog.in","r",stdin);
    freopen("ariprog.out","w",stdout);
    bool isOK=false;
    cin >> N >> M;
    memset(flag,false,sizeof(flag));

    for(int i=0;i<=M;i++)                       //预处理,标记所有的双平方数
    {
        for(int j=0;j<=M;j++)
        {
            int tmp=i*i+j*j;
            flag[tmp]=true;
        }
    }

    for(int b=1;b<=M*M;b++)
    {
        for(int a=1;a<=M*M;a++)
        {
            if(check(a,b))
            {
                cout << a << " " << b <<endl;
                isOK=true;
            }

        }
    }

    if(!isOK)
        cout << "NONE" <<endl;
    return 0;
}

  

USACO 1.4 Arithmetic Progressions

标签:

原文地址:http://www.cnblogs.com/WillsCheng/p/4795548.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!