题意:有N段木板(各段长度给定—),以及R段需要切出来的木板(各段长度给定),求用一把完美的锯子(也就是切割无损失)最多能切出R段中的多少段?
解题思路:
- 基本完全参考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;
}