USACO-Section1.4 Arithmetic Progressions

来源:互联网 发布:炫浪网络社区下载不了 编辑:程序博客网 时间:2024/06/06 00:16

2017-06-10

题目大意:

一个等差数列是一个能表示成a, a+b, a+2b,…, a+nb (n=0,1,2,3,…)的数列。
在这个问题中a是一个非负的整数,b是正整数。写一个程序来找出在双平方数集合(双平方数集合是所有能表示成p^2 + q^2的数的集合,其中p和q为非负整数)S中长度为n的等差数列。

样例输入:

5 7

样例输出:

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

题解:

这道题打个平方数的表,最大250,算出来125000不是很大,完全可以实现。没打表直接循环肯定会超时。题中采用了pair数据结构,方便按题意排序。

代码:

#include<iostream>#include<fstream>#include<cstring>#include<algorithm>using namespace std;int n , m;pair<int,int> p[10005];int bisquare[125005]; bool checkNum[125005];int main(){    ofstream cout("ariprog.out");    ifstream cin("ariprog.in");    cin >> n >> m;    int cnt = 0;    memset(bisquare , 0 ,sizeof(bisquare));    for(int i = 0;i <= m;i++){  //打表         for(int j = 0;j <= m;j++){            if(!checkNum[i * i + j * j]){                bisquare[cnt++] = i * i + j * j;                checkNum[i * i + j * j] = true;            }        }    }    sort(bisquare , bisquare + cnt);    int flag = 0;    int i , d , k;    for(i = 0;i < cnt;i++){        for(d = 1;d <= (bisquare[cnt - 1] - bisquare[0])/(n - 1);d++){            for(k = 1;k < n;k++){                if(bisquare[i] + k * d > bisquare[cnt - 1] ||!checkNum[bisquare[i] + k * d])                    break;            }            if(k == n){                p[flag].second = bisquare[i];                p[flag].first = d;                flag++;            }        }    }    sort(p , p + flag);    for(int i = 0;i < flag ;i++){        cout << p[i].second <<" " << p[i].first << endl;    }    if(flag == 0){        cout << "NONE" << endl;    }    return 0;}
原创粉丝点击