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
题意:求出一个等差数列的首项 a 和公差 d 使得前 n 项都是双平方数即可分解成 p^2+q^2 且 p、q <= m 。
分析:打表所有的双平方数,生成两个数组,一个数组用做标记 flag 另一个存储所有的双平方数 bis。然后开始枚举存储数组 bis。
心得:起初我直接打表 250*250 的所以造成 bis 数组中的值是否满足 p、q <= m 这个不好直接判断,于是我又用一个vector把所以的 p、q 打表时都存起来,于是又多了一层循环。如果输入一个 m ,再打表的话可就巧了,不仅不需要判断而且速度也快多了。
1 /* 2 ID: dizzy_l1 3 LANG: C++ 4 TASK: ariprog 5 */ 6 #include<iostream> 7 #include<algorithm> 8 #include<cstring> 9 #include<cstdio> 10 #include<vector> 11 #define MAXN 10001 12 13 using namespace std; 14 15 struct ANS 16 { 17 int a,d; 18 } ans[MAXN]; 19 bool flag[250*250*2+10]; 20 int bis[250*250*2+10],cnt,cntn,N,M; 21 22 void Init() 23 { 24 int i,j; 25 cnt=0; 26 memset(flag,false,sizeof(flag)); 27 for(i=0; i<=M; i++) 28 { 29 for(j=i; j<=M; j++) 30 { 31 if(!flag[i*i+j*j]) 32 bis[cnt++]=i*i+j*j; 33 flag[i*i+j*j]=true; 34 } 35 } 36 sort(bis,bis+cnt); 37 } 38 39 bool cmp(ANS A,ANS B) 40 { 41 if(A.d<B.d) return true; 42 if(A.d==B.d&&A.a<B.a) return true; 43 return false; 44 } 45 46 int main() 47 { 48 //freopen("ariprog.in","r",stdin); 49 //freopen("ariprog.out","w",stdout); 50 int i,j,k,d; 51 scanf("%d%d",&N,&M);N--; 52 Init(); 53 cntn=0; 54 for(i=0; i<cnt; i++) 55 { 56 for(j=i+1; j<cnt; j++) 57 { 58 d=bis[j]-bis[i]; 59 if(bis[i]+d*N>M*M*2) break; 60 for(k=1; k<=N; k++) 61 { 62 if(!flag[bis[i]+k*d]) 63 break; 64 } 65 if(k==N+1) 66 { 67 ans[cntn].a=bis[i]; 68 ans[cntn++].d=d; 69 } 70 } 71 } 72 sort(ans,ans+cntn,cmp); 73 if(cntn==0) 74 { 75 printf("NONE\n"); 76 } 77 else 78 { 79 for(i=0; i<cntn; i++) 80 printf("%d %d\n",ans[i].a,ans[i].d); 81 } 82 return 0; 83 }