题意:给你n,m ,问你在 m内两个平方数的和组成长度为n的等差数列的数列数有多少个
解题思路:暴力,递归太费时,所以要改成非递归的形式
解题代码:
1 // Arithmetic Progressions.cpp : 定义控制台应用程序的入口点。 2 // 3 4 //#include "stdafx.h" 5 6 /* 7 ID: dream.y1 8 PROG: ariprog 9 LANG: C++ 10 */ 11 12 #include <stdio.h> 13 #include <string.h> 14 #include <stdlib.h> 15 #include <time.h> 16 17 int a[260]; 18 int b[100000]; 19 int hs[500000]; 20 void dfs(int i, int j) 21 { 22 return; 23 } 24 int num = 0 ; 25 struct node{ 26 int x, y ; 27 }ans[10003]; 28 int cmp(const void *a ,const void *b) 29 { 30 if((*(node *)a).y == (*(node *)b).y) 31 return (*(node *)a).x - (*(node *)b).x; 32 else return (*(node *)a).y - (*(node *)b).y; 33 } 34 int main() 35 { 36 memset(hs,0,sizeof(hs)); 37 int n ,m ; 38 FILE *p = fopen("ariprog.in","r"); 39 FILE *p1 = fopen("ariprog.out","w"); 40 fscanf(p,"%d %d",&n,&m); 41 for(int i = 1; i <= m;i ++) 42 { 43 a[i] = i * i ; 44 hs[a[i]] = 1; 45 } 46 // printf("%d ",a[250]); 47 int k = 0 ; 48 49 for(int i = 1;i <= m ;i ++) 50 for(int j = i;j <= m ;j ++) 51 { 52 hs[a[i]+a[j]] = 1; 53 } 54 55 k = 0; 56 hs[0] = 1; 57 for(int i = 0 ;i <= 140000;i ++) 58 { 59 if(hs[i]) 60 { 61 b[++k] = i; 62 } 63 } 64 //printf("**%d ",k); 65 for(int i = 1; i<= k;i ++) 66 { 67 for(int j =i+1; j <= k; j ++ ) 68 { 69 int ti = b[j] ; 70 int temp = b[j] - b[i]; 71 int step = 0 ; 72 while(hs[ti]) 73 { 74 step ++; 75 ti = ti + temp; 76 } 77 // printf("%d %d %d ",b[i],temp,step); 78 if(step >= n -1) 79 { 80 //printf("%d %d %d ",b[i],temp,step); 81 num ++; 82 ans[num].x = b[i]; 83 ans[num].y = temp; 84 } 85 } 86 //printf("%d ",b[i]); 87 } 88 89 90 qsort(ans+1,num,sizeof(node),cmp); 91 for(int i = 1;i <= num; i++) 92 fprintf(p1,"%d %d ",ans[i].x,ans[i].y); 93 if(num == 0 ) 94 fprintf(p1,"NONE "); 95 fclose(p); 96 fclose(p1); 97 return 0 ; 98 }