《算法竞赛入门经典2ndEdition 》--Chapter 2 习题解答(Page 34-35)

   本蒟蒻的第一篇,希望大家捧场。 考完noip,发现了自己的不足,准备开始看这本《算法竞赛入门经典2ndEdition 》 ,希望自己能够坚持下来并且有所提升,加油!
   不多说了,上答案。
   有错误请大家多指正。

Exercise2-1 daffodil

#include "stdio.h"
int main()
{
  for(int a = 1; a <= 9; a++)
    for(int b = 0; b <= 9; b++)
      for(int c = 0; c <= 9; c++)
      {
        int n = a*100 + b*10 + c;
        if(n == a*a*a + b*b*b + c*c*c)
          printf("%d ",n);
      } 
  getchar();getchar();
  return 0;
} 



//#include "stdio.h"
//int main()
//{
//  for(int abc = 100; abc <= 999; abc++)
//  {
//    int a = abc/100, b = abc%100/10, c = abc%10;
//    if(abc == a*a*a + b*b*b + c*c*c) printf("%d ",abc);
//  } 
//  getchar();getchar();
//  return 0;
//}

Exercise2-2 hanxin

#include "stdio.h"
int main()
{
  int a, b, c, cnt = 0;
  while(scanf("%d%d%d", &a, &b, &c) != EOF)
  {
    int flag = 0;
    for(int n = 10; n <= 100; n++)
      if(n%3 == a && n%5 == b && n%7 == c)
      {
        flag = n;
        break;
      }
    if(flag != 0) 
      printf("Case %d: %d\n", ++cnt, flag);
    else printf("Case %d: No answer\n", ++cnt);
  }
  getchar();
  return 0;
} 

Exercise2-3 triangle

#include "stdio.h"
#include "time.h"
int main()
{
  int n;
  scanf("%d",&n);
  for(int i = 1; i <= n; i++)
  {
    for(int j = 1; j < i; j++) printf(" ");
    for(int j = 1; j <= 2*(n-i) + 1; j++) printf("#");
    printf("\n");
  }
  printf("%.2f",(double)clock()/CLOCKS_PER_SEC);
  getchar();getchar();
  return 0;
} 

Exercise2-4 subsequence

#include "stdio.h"
int main()
{
  int n,m,kase = 0;
  while(scanf("%d%d",&n,&m) != EOF && n && m)
  {
    double sum = 0;
    for(int x = n; x <= m; x++)
    {
      double y = 1.0 / x;
      y *= y;
      sum += y;
    }
    printf("Case %d: %.5lf\n",++kase,sum);
  }

  getchar();getchar();
  return 0;
} 

Exercise2-5 decimal

#include "stdio.h"
int main()
{
  int a, b, c, kase = 0;
  while(scanf("%d%d%d",&a,&b,&c) != EOF && a && b && c)
  {

    printf("Case %d: %d.",++kase, a / b);
    a -= (a/b)*b;
    for(int i = 1; i <= c; i++)
    {
      a *= 10;
      printf("%d", a / b);
      a -= (a/b)*b; 
    }
    printf("\n");
  } 
  getchar();getchar();
  return 0;
} 

Exercise2-6 permutation

#include "stdio.h"
#include "string.h"
int main()
{
  int num[10];
  for(int x = 102; x <= 329; x++)
  {
    int sum = 0;
    memset(num, 0, sizeof(num));
    int y = x;
    for(int i = 1; i <= 3; i++,y += x)
    {
      num[y / 100] = 1; 
      num[y % 100 / 10] = 1;
      num[y % 10] = 1;
    }
    for(int i = 0; i <= 9; i++)
      sum += num[i];
    if(sum == 9) 
      printf("%d %d %d\n",x,2*x,3*x); 
  }
  getchar();getchar();
  return 0;
} 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值