Fence Rails

题意:有N段木板(各段长度给定—),以及R段需要切出来的木板(各段长度给定),求用一把完美的锯子(也就是切割无损失)最多能切出R段中的多少段?

解题思路

  1. 基本完全参考SHFACM这篇博客上的思想和代码(http://www.cppblog.com/SHFACM/articles/72711.html?opt=admin

代码

/*
ID: zc.rene1
LANG: C
PROG: fence8
 */

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

FILE *fout;
int N, R, total, max = -1, waste, max_waste;
int boards[51];
int remains[51];
int rails[1024];
int sum[1024];
int which_board[1024];

void GetInput(FILE *fin)
{
    int i;

    total = 0;

    fscanf(fin, "%d", &N);
    for(i=1; i<=N; i++)
    {
	fscanf(fin, "%d", &boards[i]);
	total += boards[i];
    }
    fscanf(fin, "%d", &R);
    for(i=1; i<=R; i++)
    {
	fscanf(fin, "%d", &rails[i]);
    }
}

void Sort(int *a, int len, int model)
{
    int i, j;

    for (j=len; j>1; j--)
    {
	for (i=1; i<j; i++)
	{
	    if (model == 0)
	    {
		if (a[i] > a[i + 1])
		{
		    a[0] = a[i];
		    a[i] = a[i + 1];
		    a[i + 1] = a[0];
		}
	    }
	    else
	    {
		if (a[i] < a[i + 1])
		{
		    a[0] = a[i];
		    a[i] = a[i + 1];
		    a[i + 1] = a[0];
		}
	    }
	}
    }
}

void DFS(int depth, int index, int original_depth)
{
    int i;
    if (depth == 0)
    {
	fprintf(fout, "%d\n", original_depth);
	exit(0);
    }
    for (i=index; i<=N; i++)
    {
	if (remains[i] >= rails[depth])
	{
	    int waste_cp = waste;
	    remains[i] -= rails[depth];

	    if ((remains[i] < rails[1]) && (waste + remains[i] > max_waste))
	    {
		remains[i] += rails[depth];
		continue;
	    }

	    if (remains[i] < rails[1])
	    {
		waste += remains[i];
	    }

	    if ((depth >= 2) && (rails[depth - 1] == rails[depth]))
	    {
		DFS(depth - 1, i, original_depth);
	    }
	    else
	    {
		DFS(depth - 1, 1, original_depth);
	    }
	    remains[i] += rails[depth];
	    waste = waste_cp;
	}
    }	
}

int main(void)
{
    FILE *fin;
    int i, j;

    fin = fopen("fence8.in", "r");
    fout = fopen("fence8.out", "w");

    GetInput(fin);
    Sort(boards, N, 0);
    Sort(rails, R, 0);
    memcpy(remains, boards, (N + 1) * sizeof(int));

    sum[1] = rails[1];
    j = 1;
    while ((j <= R) && (sum[j] <= total))
    {
	j++;
	sum[j] = sum[j - 1] + rails[j];
    }

    for (i=j - 1; i>=0; i--)
    {
	waste = 0;
	max_waste = total - sum[i];
	DFS(i, 1, i);
    }

    return 0;
}













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值