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

时间:2022-12-25 15:04:23

习题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;
}