这道题我一看蛮简单,写了50来行,结果time limit execeeded.后来搜了搜,知道了,是自己把等差写在外面而且是从1开始增。。。
要是遇到p》100的话,最大数字是100*100*2=20000; 从1开始看,再在1下找是否存在,差不多有20000*100*100/2就是一亿了。。。,这个的确是太多了。当初这么做也是因为看答案是要求按d来升序排的。要是在生成的双平方数中搜,双平方大约有100*100/2个,5000个外层循环,里面可以精简不少,因为d可以从相邻的两个双平方数中得到,即d的初值和递增再也不是1和++,这样就非常高效。看了许多代码,下面一个我最喜欢,我也学习到了algorithm一个排序函数sort(),很好可以通过自己巧妙地定义比较函数,来实现加权排序。了不起。
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 singe 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
为了复习一遍,这次代码我自己打一遍;
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX=250*250*2+10; //+10,I don't understand clearly;
bool flag[MAX]={};
int leg[MAX],size=0,res_cnt=0;
struct re
{
int a,b;
bool operator < (const re& x) const
{
return b<x.b||b==x.b&&a<x.a;
}
}res[10000];
int main()
{
freopen("ariprog.in","r",stdin);
freopen("ariprog.out","w",stdout);
int n,m;
cin>>n>>m;
int max=m*m*2;
for(int i=0; i<=m; ++i)
for(int j=i; j<=m; ++j)
flag[i*i+j*j]=1;
for(int i=0; i<=max;++i) if(flag[i]) leg[size++]=i;
for(int i=0; i<size; ++i)
for(int j=i+1; j<size; ++j)
{
int d=leg[j]-leg[i];
if(leg[i]+(n-1)*d>max) break;
for(int k=2; k<n; ++k)
if(!flag[leg[i]+k*d]) goto L1;
res[res_cnt].a=leg[i];
res[res_cnt++].b=d;
L1: ;
}
sort(res,res+res_cnt);
if(!res_cnt) cout<<"NONE"<<endl;
else
for(int i=0; i<res_cnt; ++i) cout<<res[i].a<<' '<<res[i].b<<endl;
return 0;
}
代码非常清楚,精简。测试数据中最大的0.41s,很不错。
学习!