Wooden Sticks
Problem Description
There is a pile of n wooden sticks. The length and weight of each stick are known in advance. The sticks are to be processed by a woodworking machine in one by one fashion. It needs some time, called setup time, for the machine to prepare processing a stick. The setup times are associated with cleaning operations and changing tools and shapes in the machine. The setup times of the woodworking machine are given as follows:
(a) The setup time for the first wooden stick is 1 minute.
(b) Right after processing a stick of length l and weight w , the machine will need no setup time for a stick of length l' and weight w' if l<=l' and w<=w'. Otherwise, it will need 1 minute for setup.
You are to find the minimum setup time to process a given pile of n wooden sticks. For example, if you have five sticks whose pairs of length and weight are (4,9), (5,2), (2,1), (3,5), and (1,4), then the minimum setup time should be 2 minutes since there is a sequence of pairs (1,4), (3,5), (4,9), (2,1), (5,2).
Input
The input consists of T test cases. The number of test cases (T) is given in the first line of the input file. Each test case consists of two lines: The first line has an integer n , 1<=n<=5000, that represents the number of wooden sticks in the test case, and the second line contains n 2 positive integers l1, w1, l2, w2, ..., ln, wn, each of magnitude at most 10000 , where li and wi are the length and weight of the i th wooden stick, respectively. The 2n integers are delimited by one or more spaces.
Output
The output should contain the minimum setup time in minutes, one per line.
Sample Input
3
5
4 9 5 2 2 1 3 5 1 4
3
2 2 1 1 2 2
3
1 3 2 2 3 1
Sample Output
2
1
3
典型的贪心算法题目,
题目大体内容:有一个锯木机(就这么认为吧。。。)
它每次切割的木头长度和重量都要比上次切割的木头的长度和重量要大或等,
比如第一次切割长度为2,重量为3,第二次切割的木头长度必须大于等于2,
同时,重量也要大于等于3,这样切割不会花时间准备,
否则就要花1分钟准备,给出一堆木头,求总共要多少准备时间。
其实,这道题算比较简单的贪心题目,排序然后计算就行了,但是我WA很多次,
我的方法是,建立一个木头的结构体,里面有 长度len,重量wei,切割与否的bool型use,
输入数据,然后排序,从第一块开始切割,切割后use=false(所有木头初始use为true),
往后检查是否合格,合格就切割,并将切割的use设置为false,
第一轮切割完,时间++,再从头检查use,从不为false的开始第二轮切割,
切到最后所有的木头use均为false结束。
WA的原因,排序部分,我只按长度排序,而且长度相等的情况没有考虑,
所以按我的算法 如果输入2块木头为: 2 2,2 1
它将用2分钟准备,显然是错的,所以在排序中比较长度相等的情况就AC了。。。。
我的程序:
#include <iostream>
using namespace std;
struct wooden{
int len,wei;
bool use;
}wd[5001];
int main()
{
int T,N,total; //T为组数,N为行数,total 总用时
int i,j,temp;
wooden tem;
cin>>T;
while(T--)
{
//*******输入********
cin>>N;
for(i=0;i<N;++i)
{
cin>>wd[i].len>>wd[i].wei;
wd[i].use=1;
}
//*******排序********
for(i=0;i<N-1;++i)
for(j=i+1;j<N;++j)
{
if(wd[i].len==wd[j].len)
{
if(wd[i].wei>wd[j].wei)
{
tem=wd[i];
wd[i]=wd[j];
wd[j]=tem;
}
}
else if(wd[i].len>wd[j].len)
{
tem=wd[i];
wd[i]=wd[j];
wd[j]=tem;
}
}
//*******计算********
total=0;
for(i=0;i<N;++i)
{
if(!wd[i].use)
continue;
temp=i;
for(j=i+1;j<N;++j)
{
if(!wd[j].use)
continue;
if(wd[j].len>=wd[temp].len && wd[j].wei>=wd[temp].wei)
{
wd[j].use=false;
temp=j;
}
}
++total;
}
cout<<total<<endl;
}
return 0;
}