算法竞赛入门经典第二版——第一章例题

算法竞赛入门经典第二版——第一章例题

例题 1-1 圆柱体的表面积

输入底面半径r和高h,输出圆柱体的表面积,保留三位小数,格式:

样例输入:
3.5 9
样例输出:
Area = 274.889

代码:

#include <stdio.h>
#include <math.h>

int main()
{
    const double pi = acos(-1.0);
    double r, h, s1, s2, s;
    scanf("%lf%lf", &r, &h);
    s1 = pi * r * r;
    s2 = 2 * pi * r * h;
    s = s1 * 2 + s2;
    printf("Area = %.3f
", s);
    return 0;
}

例题1-2 三位数反转

输入一个三位数,分离出它的百位、十位和个位,反转后输出。

样例输入:
127
样例输出:
721

代码:

#include <stdio.h>

int main()
{
    int n;
    scanf("%d", &n);
    printf("%d%d%d", n % 10, n / 10 % 10, n / 100);
}

例题 1-3 交换变量

输入两个整数ab,交换二者的值,然后输出。

样例输入:
824 16
样例输出:
16 824

代码:

#include <stdio.h>

int main()
{
    int a, b, c;
    scanf("%d%d", &a, &b);
    c = a;
    a = b;
    b = c;
    printf("%d %d", a, b);
}

例题 1-4 鸡兔同笼

已知鸡和兔的总数量为n,总腿数为m。输入nm每一次输出鸡的数目和兔的数目。如果无解,则输出No answer

样例输入:
14 32
样例输出:
12 2
样例输入:
10 16
样例输出:
No answer

代码:

#include <stdio.h>

int main()
{
    int a, b, n, m;
    scanf("%d%d", &n, &m);
    a = (4 * n - m) / 2;
    b = n - a;
    if (m % 2 == 1 || a < 0 || b < 0)
    {
        printf("No answer
");
    }
    else
    {
        printf("%d %d
", a, b);
    }
    return 0;
}

例题 1-5 三整数排序

输入3个整数,从小到大排序后输出。

样例输入:
20 7 33
样例输出:
7 20 33

代码:

#include <stdio.h>

int main()
{
    int a, b, c, d;
    scanf("%d%d%d", &a, &b, &c);
    if (a > b)
    {
        d = a;
        a = b;
        b = d;
    }
    if (a > c)
    {
        d = a;
        a = c;
        c = d;
    }
    if (b > c)
    {
        d = c;
        c = b;
        b = d;
    }
    printf("%d %d %d", a, b, c);
}
原文地址:https://www.cnblogs.com/techoc/p/13472634.html