HDU1051 Wooden Sticks

来源:互联网 发布:mac爱奇艺 编辑:程序博客网 时间:2024/05/17 03:01

题目:
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
213
题目大意是:有一些木棍,知道它们的长度和重量,每当要处理更短或更轻的木棍时,都需要花1分钟准备,问至少要多久。

分析:这是一道贪心题,要考虑长度和重量。先排序(优先按长度由短到长,其次按重量由轻到重),排序后则不用过多考虑长度,比较重量即可。

思路:先将数组排序,以a[ 0 ]为标准,与数组元素依次比较重量w。符合要求的元素被赋值成最长最重的棍子(即第n根)(再次排序则可将a[ i ]调到最后,同时n--,这样就排除出数组,不妨碍下一轮的比较)。

代码如下:

#include<cstdio>#include<iostream>#include<algorithm>using namespace std;const int maxn=5000+20;struct size{int l,w;} a[maxn],s[1];//s[0]记录当前比较的标准 bool cmp(const size a,const size b ){//优先排长度,长度相等排重量 if( a.l < b.l )  return 1;    else if( a.l == b.l ){        if( a.w < b.w )  return 1;        else  return 0;}    else return 0;}int main(){int t,n;cin>>t;while(t--){int k=0;//k 为机器setup的次数 cin>>n;for(int i=0;i<n;i++){    cin>>a[i].l>>a[i].w;}sort(a,a+n,cmp);while(n>0){k++;int m=n;   //这一轮的棍子个数 s[0]=a[0]; //机器setup for(int i=0;i<m;i++){if(s[0].w<=a[i].w){s[0]=a[i];a[i]=a[m-1];n--;}}//循环完之后 n为下一轮棍子个数 sort(a,a+m,cmp); } printf("%d\n",k);}return 0;}


0 0
原创粉丝点击