1:问题描述
Problem DescriptionThere 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).
InputThe 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.
OutputThe 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:大致题意
现在有n个木棒,输入它们的长度和重量。用一个机器制作它们,机器在运作之前需要准备的时间。第1根木棒需要1min的时间,如果第2根的长度和重量都大于第1根,那么就不需要准备时间。否则的话需要1min进行准备。
现在输入 木棒的个数n和它们的长度和重量。对它们合理的排序,求出最少的时间。
3:思路
典型的贪心问题。首先对木棒的长度进行排序。长度相同的话就按照重量排序。长度排好以后,只要后面的重量大于前面的重量,就可以不花费时间。说白了就是求重量的最长递增子序列。下面配张图方便大家理解。
4:感想
这个题也算是贪心的一个基本题型吧。
5:ac代码
#include<iostream>
#include<string.h>
#include<set>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<numeric>
#include<math.h>
#include<string.h>
#include<sstream>
#include<stdio.h>
#include<string>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<map>
#include<queue>
using namespace std;
struct stick
{
int l;
int w;
};
bool cmp(const stick &a,const stick &b)
{
if(a.l<b.l) return true;
else if(a.l==b.l)return a.w<b.w;
return false;
}
int main()
{
vector<stick>ww;
vector<stick>::iterator it;
stick z;
int a[5005];
int n,i,k,e,t,L,W,max,j,x,N;
cin>>N;
while(N--)
{
t=0;
cin>>n;
ww.clear();
for(i=0;i<n;i++)
{
cin>>L>>W;
z.l=L;
z.w=W;
ww.push_back(z);
}
sort(ww.begin(),ww.end(),cmp);
memset(a,0,sizeof(a));
for(k=0;k<n;k++)
{
if(a[k]==1) continue;
t++;
max=ww[k].w;
a[k]=1;
for(e=k+1;e<n;e++)
{
if(max<=ww[e].w&&a[e]==0) {max=ww[e].w;a[e]=1;}
}
x=0;
for(j=0;j<n;j++) if(a[j]==1) x++;//完成
if(x==n) break;
}
cout<<t<<endl;
}
return 0;
}