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).
(下面是翻译)
有一堆木棍。每根棍子的长度和重量都是事先知道的。木棍要用木工机器一根一根地加工。机器准备加工木棒需要一些时间,称为设置时间。设置时间与清洁操作和更换机器中的工具和形状有关。木工机床的设置时间如下:
(b) 在处理长度为l且重量为w的斗杆之后,如果l<=l'且w<=w',则机器不需要设置长度为l'且重量为w'的斗杆的时间。否则,安装需要1分钟。
你要找到最短的设置时间来处理一堆给定的n木棍。例如,如果您有五根长度和重量为(4,9)、(5,2)、(2,1)、(3,5)和(1,4)的木棒,则最小设置时间应为2分钟,因为存在一系列木棒(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
思路
使用贪心算法,先将木棍排序(两个关键字依次升序),用数组p存储木棍是否已经被处理(未被处理为0),然后从头遍历,碰到第一个根p!=0的木棍,存储其长和重,记为curl和curw,继续往后遍历,对每根p!=0的木棍,若其l>=curl&&w>=curw为真,则处理这根木棍,并更新curl和curw;反复循环直至所有木棍被处理。
代码
#include<bits/stdc++.h>
using namespace std;
int a[5001],b[5001];
class mugun
{
public:
mugun(){}
mugun(int l1,int w1)
{
l=l1;
w=w1;
}
int l;
int w;
};
mugun mg[5000];
bool cmp(mugun mg1,mugun mg2)
{
if(mg1.l!=mg2.l) return mg1.l<mg2.l;
else return mg1.w<mg2.w;
}
int main()
{
int T;
cin>>T;
while(T--)
{
int n;
cin>>n;
for(int i=0;i<n;i++) cin>>mg[i].l>>mg[i].w;
sort(mg,mg+n,cmp);
bool p[n];
memset(p,0,sizeof(p));
// for(int i=0;i<n;i++) cout<<mg[i].l<<' '<<mg[i].w<<'\n';
int t=0;
while(1)
{
int i=0;
for(;i<n;i++)
{
if(!p[i]) break;
}
if(i==n) break;//全部判断
t++;
int curl=mg[i].l,curw=mg[i].w;
for(;i<n;i++)
if(mg[i].l>=curl&&mg[i].w>=curw&&p[i]==0)
{
curl=mg[i].l;
curw=mg[i].w;
p[i]=1;
}
}
cout<<t<<'\n';
}
}