题意:将一个数拆成若干个连续数字的平方和。
用尺取法枚举区间,复杂度为O(n),时限10s,3s多ac。
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <cmath> 5 using namespace std; 6 7 const int N = 100; 8 9 struct Node 10 { 11 int from, to; 12 } node[N]; 13 14 void solve( long long n ) 15 { 16 int u = sqrt( n * 1.0 ), cnt = 0, q = 1; 17 long long sum = 0; 18 for ( int i = 1; i <= u; i++ ) 19 { 20 sum += ( long long ) i * i; 21 while ( sum > n ) 22 { 23 sum -= ( long long ) q * q; 24 q++; 25 } 26 if ( sum == n ) 27 { 28 node[cnt].from = q; 29 node[cnt].to = i; 30 cnt++; 31 } 32 } 33 printf("%d\n", cnt); 34 for ( int i = 0; i < cnt; i++ ) 35 { 36 printf("%d", node[i].to - node[i].from + 1); 37 for ( int j = node[i].from; j <= node[i].to; j++ ) 38 { 39 printf(" %d", j); 40 } 41 puts(""); 42 } 43 } 44 45 int main () 46 { 47 long long n; 48 while ( scanf("%lld", &n) != EOF ) 49 { 50 solve(n); 51 } 52 return 0; 53 }
时间: 2024-10-11 04:14:57