《算法竞赛入门经典》习题——Chapter 2
习题2-1 位数(digit)
1 #include <stdio.h> 2 void main() 3 { 4 int n,number=0; 5 scanf("%d", &n); 6 while(n!=0) 7 { 8 n /= 10; 9 number++; 10 } 11 printf("%d\n",number); 12 }
习题2-2 水仙花数(daffodil)
#include <stdio.h> void main() { int i; int a,b,c; for (i=100;i<1000;i++) { a = i/100; b = i/10%10; c = i%10; if (a*a*a+b*b*b+c*c*c==i) { printf("%d ",i); } } printf("\n"); }
习题2-3韩信点兵(hanxin)
1 #include <stdio.h> 2 void main() 3 { 4 int n,m,q; 5 bool success = false; 6 scanf("%d%d%d", &n, &m, &q); 7 8 for (int i=1;i<100;i++) 9 { 10 if (i%3==n && i%5==m && i%7==q) 11 { 12 printf("%d\n",i); 13 success = true; 14 break; 15 } 16 } 17 if (!success) //或者可以用i == 100 18 { 19 printf("No answer\n"); 20 } 21 }
习题2-4 倒三角形(triangle)
1 #include <stdio.h> 2 void main() 3 { 4 int i,n,m,j; 5 scanf("%d", &n); 6 7 for (i=n;i>0;i--) 8 { 9 for (m=0;m<n-i;m++) 10 { 11 printf(" "); 12 } 13 for (j=2*i-1;j>0;j--) 14 { 15 16 printf("#"); 17 } 18 printf("\n"); 19 } 20 }
习题2-5 统计(stat)
1 #include <stdio.h> 2 #include <stdlib.h> 3 void main() 4 { 5 int i,n,m,number=0; 6 int *p; 7 scanf("%d", &n); 8 p = (int*)malloc(sizeof(int)*n); 9 for(i=0;i<n;i++) 10 { 11 scanf("%d",&p[i]); 12 } 13 scanf("%d", &m); 14 for(i=0;i<n;i++) 15 { 16 if (p[i]<m) 17 { 18 number++; 19 } 20 } 21 printf("%d",number); 22 }
使用重定向时做如下修改
1 #define LOCAL 2 #include <stdio.h> 3 #include <stdlib.h> 4 void main() 5 { 6 #ifdef LOCAL 7 freopen("data.in","r",stdin); 8 freopen("data.out","w",stdout); 9 #endif 10 //后面一样
习题2-6 调和函数(harmony)
#include <stdio.h> void main() { int n,i; double sum = 0; scanf("%d",&n); for (i=1; i <=n;i++) { sum += 1.0/i; } printf("%.3lf",sum); }
习题2-7近似计算(approximation)
1 #include <stdio.h> 2 #include <math.h> 3 void main() 4 { 5 int n,m,q; 6 double flag = -1; 7 double sum = 0; 8 double tmp; 9 for (int i=1;;i+=2) 10 { 11 flag = -1 * flag; 12 tmp = flag/i; 13 // printf("%lf\n",tmp); 14 sum += tmp; 15 16 if (fabs(tmp)<10e-6) 17 { 18 break; 19 } 20 } 21 printf("pi = %lf\n",4*sum); 22 }
习题2-8 子序列的和(subsequence)
#include <stdio.h> #include <stdlib.h> void main() { int i,n,m; double sum=0; scanf("%d%d",&n,&m); for (i=n;i<=m;i++) { sum+=1.0/i/i; //陷阱是n较大时n*n容易溢出 } printf("%.5lf",sum); }
习题2-9 分数化小数
1 #include <stdio.h> 2 int main(void) 3 { 4 int a, b, c; 5 double x; 6 scanf("%d%d%d", &a, &b, &c); 7 x = 1.0*a/b; 8 printf("%.*lf\n", c, x); //printf("%*.*lf", x, y, z) 第一个*对应x,第二个*对应y,lf对应z 9 return 0; 10 }
习题2-10 排列(permutation)
1 #include <stdio.h> 2 int main(void) 3 { 4 int x, y, z, a[10] = {0}; 5 for(x = 100; x < 333; x++) 6 { 7 y = 2*x; 8 z = 3*x; 9 //令a[出现的数字] = 1 10 a[x/100] = a[x/10%10] = a[x%10] = 1; 11 a[y/100] = a[y/10%10] = a[y%10] = 1; 12 a[z/100] = a[z/10%10] = a[z%10] = 1; 13 int i, s = 0; 14 for(i = 1; i < 10; i++) 15 s += a[i]; 16 if(s == 9) 17 printf("%d\t%d\t%d\n", x, y, z); 18 for(i = 1; i < 10; i++) //重新赋值为0 19 a[i] = 0; 20 } 21 return 0; 22 }
参考地址http://blog.csdn.net/litiouslove/article/details/7891700