【2022】余料最少

Time Limit: 3 second
Memory Limit: 2 MB

【问题描述】

将一根长为Xcm的钢管截成长为69cm和39cm两种规格的短料。在这两种规格的短料至少各截一根的前提下, 如何截才能余料最少。如果X<108CM,输出“error”。

【输入】

一行,钢管的初始长度

【输出】

共三行。第一行是长为69CM的钢管数量,第二行是长为39CM的钢管数量,第三行为余料的长度。

【输入样例】

369

【输出样例】

3
4
6

【题解】

只要无脑深搜就好,挺简单的,以当前使用的长度为search函数里的变量。不断尝试不同的长度即可。

【代码】

#include 
#include 

const int MAXN = 100;

int c,rest,a[MAXN],minrest,a39,a69; //rest是当前实时更新的余料,minrest是最优解a39,a69是最优方案,实时的方案放在a[39]和a[69];

void input_data()
{
    scanf("%d",&c);
    if (c < 108) //特判错误信息。
        {
            printf("error");
            exit(0);
        }
    rest = c - 108; //获取剩余的料
    minrest = rest;
    a[39] = 1;a[69] = 1; //初始化最优解和实时解、
    a39 = 1;a69 = 1;
}

void sear_ch(int t) //搜索长度为t的情况
{
    a[t]++; //t长度的使用根数++
    rest-=t;
    if (rest < minrest) //尝试更新最优解
        {
            minrest = rest;
            a39 = a[39];a69 = a[69];
        }
    if (rest >= 69) //再继续搜
        sear_ch(69);
    if (rest >=39)
        sear_ch(39);
    rest+=t; //回溯
    a[t]--;
}

void get_ans() //判断一下能否用这个长度,然后就搜索。
{
    if (rest >= 69)
        sear_ch(69);
    if (rest >=39)
        sear_ch(39);
}

void output_ans()
{
    printf("%d\n",a69);
    printf("%d\n",a39);
    printf("%d\n",minrest);
}

int main()
{
    input_data();
    get_ans();
    output_ans();
    return 0;
}


 

转载于:https://www.cnblogs.com/AWCXV/p/7632476.html

你可能感兴趣的:(【2022】余料最少)