描述
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).
输入
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.输出
The output should contain the minimum setup time in minutes, one per line.
这题其实就是在找递增子序列。
对于这个题:思路在于先排序,再用变量标记有没有加入。
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include<string>
using namespace std;
typedef long long LL;
const int N = 5005;
struct Node
{int st,et,ok;//ok变量标记是否加工过了
}p[N];
bool cmp(Node a,Node b)//这里排序注意,是按开始的时间升序排,当开始的时间相同时,注意要把结束时间按升序排,不然就无法实现
{if(a.st == b.st) return a.et < b.et;else return a.st < b.st;
}
int main()
{int t,n,i,j,maxet,time;scanf("%d",&t);while(t--){scanf("%d",&n);for(i=0;i<n;++i) scanf("%d %d",&p[i].st,&p[i].et);for(i=0;i<n;++i) p[i].ok = 0;sort(p,p+n,cmp);time = 0;for(i=0;i<n-1;++i)//注意最后一个不用当做头元素开搜,在循环结束后特判,因为最后一个元素在下面的for循环根本无法进入。{if(p[i].ok != 1)//该处没有用过就从这里开搜,这个剪枝能让时间复杂度下降很多{p[i].ok = 1;maxet = p[i].et;for(j=i+1;j<n;++j){if(p[j].ok != 1 && p[j].et >= maxet){p[j].ok = 1;maxet = p[j].et;}}time++;}}if(p[n-1].ok != 1) time++;//对最后一个元素的特判printf("%d\n",time);}
}