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
时间不超过5s,之前考虑到的只有双平方对称、从小到大排序、以及a+(n-1)b〉maxx的情况,a和b还分别从0,1穷举弱爆了。。然后发现要快就直接抽table里面的元素,然后生成table要做个标记。。。还是超时,所以有关搜索的就只有判断是否存在table的函数了,既然用了sort,那就再用一下<algorithm>的二分搜索函数binary_search(a,a+b,ele)嗯
/*
ID: des_jas1
PROG: ariprog
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <algorithm>
#include <vector>
#define fin cin
#define fout cout
using namespace std;
typedef struct seq
{
int a;
int b;
}seq;
const int MAXN=10000,MAX=62500;
int table[MAX+5],n,M,maxx,r=0;
seq ans[MAXN+5];
bool flag[MAX]={0};
bool cmp(seq t1,seq t2)
{
if(t1.b!=t2.b)
return t1.b<t2.b;
else
return t1.a<t2.a;
}
void createtable()
{
int i,j,temp;
for(i=0;i<=M;i++)
for(j=i;j<=M;j++) //矩阵的一半
{
temp=i*i+j*j;
if(!flag[temp])
{
table[r]=temp;
r++;
flag[temp]=true;
}
}
}
/*bool IS_IN(int p)
{
int i;
for(i=0;i<r;i++)
{
if(p==table[i])
return true;
if(p<table[i])
return false;
}
return false;
} */
int main()
{
ofstream fout ("ariprog.out");
ifstream fin ("ariprog.in");
int i,j,d,tp=1,cn=0,q=0;
fin>>n>>M;
maxx=M*M*2;
createtable();
sort(table,table+r);
for(i=0;i<r;i++)
for(j=i+1;j<r;j++)
{
d=table[j]-table[i];
if(table[i]+(n-1)*d>maxx)
break;
for(cn=2;cn<n;cn++)
{
tp=table[i]+d*cn;
if(!binary_search(table,table+r,tp))
break;
}
if(cn==n)
{
ans[q].a=table[i];
ans[q].b=d;
q++;
}
}
sort(ans,ans+q,cmp);
if(!q)
fout<<"NONE"<<endl;
else
{
for(i=0;i<q;i++)
fout<<ans[i].a<<" "<<ans[i].b<<endl;
}
fout.close();
fin.close();
return 0;
}