《算法竞赛入门经典 第二版》习题——Chapter 2

习题2-1 水仙花数(daffodil)

#include<iostream>
#include<cstdio>
using namespace std;

int main()
{
	int a, b, c;
	for (int num = 100; num < 1000; num++)
	{
		a = num / 100;
		b = num / 10 % 10;
		c = num % 10;

		if (num == a*a*a + b*b*b + c*c*c)
			cout << num << " ";
	}
	cout << endl;
}

#include<iostream>
#include<cstdio>
using namespace std;

int main()
{
	for (int num = 100; num < 1000; num++)
	{
		int temp = num;
		int s = 0, a;
		while (temp)
		{
			a = temp % 10;
			s += a*a*a;
			temp /= 10;
		}

		if (num == s)
			cout << num << " ";
	}
	cout << endl;
}


习题2-2 韩信点兵(hanxin)

#include<iostream>
#include<cstdio>
using namespace std;


int main()
{
	int a, b, c;
	int count = 0;
	while (cin >> a >> b >> c)
	{
		++count;
		int i;
		for (i = 10; i <= 100; i++)
		{
			if (i % 3 == a && i % 5 == b && i % 7 == c)
			{
				printf("Case %d: %d\n", count, i);
				break;
			}
		}
		if (i == 101)
		{
			printf("Case %d: No answer\n", count);
		}
	}
}


习题2-3 倒三角形(triangle)

#include<iostream>
#include<cstdio>
using namespace std;


int main()
{
	int n,b=0;
	cin >> n;
	for (; n > 0; n--,b++)
	{
		for (int i = 0; i < b; i++)
			cout << " ";
		for (int j = 2*n-1; j >0; j--)
		{
			cout << "#";
		}
		cout << endl;
	}
	return 0;
}


习题2-4 子序列的和(subsequence)

分析:本题陷阱在于n比较大时,n*n会溢出,可以用1/n/n替代1/n^2,或者将n*n强制转换为double

#include<iostream>
#include<cstdio>
using namespace std;


int main()
{
	int  n, m;
	int kase = 0;
	while (cin >> n >> m && m!=0 || n!=0)
	{
		++kase;
		double s = 0;
		for (long long  i = n; i <= m; i++)
		{
			s += 1 / double(i*i);
		}
		printf("Case %d: %.5f\n", kase, s);

	}
	return 0;
}



习题2-5 分数化小数(decimal)

分析:printf("%*.*lf", x, y, z) 第一个*对应x,第二个*对应y,lf对应z (高级特性)

注:该方案不完善,有 bug~

#include<iostream>
#include<cstdio>
using namespace std;


int main()
{
	int  a, b;
	int c = 0,kase=0;
	while (cin >> a >> b >> c && a!=0 || b!=0 || c!=0)
	{
		++kase;
		double f =1.0 * a /b;
		printf("Case %d: %.*lf",kase, c, f);
		
	}
	return 0;
}


习题2-6 排列(permulation)

分析:思路其实就是穷举,首先可以判断出最小的数在123~329之间。利用一个数组a[1]~a[9],值为0表示没出现过,为1则表示出现,注意最后要清零!

#include<iostream>
#include<cstdio>
using namespace std;


int main()
{
	int a[10] = { 0 };
	int b;
	for (int i = 123; i <= 329; i++)
	{
		for (int j = 1; j <= 3; j++)
		{
			int temp = i*j;
			while (temp)
			{
				b = temp % 10;
				a[b] = 1;
				temp /= 10;
			}
		}
		b = 0;
		for (int k = 1; k < 10; k++)
			b += a[k];
		if (b == 9)
			printf("%d %d %d\n", i, i * 2, i * 3);
		for (int k = 0; k < 10; k++)
			a[k] = 0;
	}
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值