我觉得我的想法蛮好的,我的算法类似一个贪吃蛇,先对长度排序,若长度相等,则对重量排序。因为满足最大子集的条件是长度大于等于下个长度,并且重量也要大于等于下个重量,因此遍历,把最大子集找出并合并。visited数组则可以减少时间复杂度,减少不必要的遍历。我觉得这个算法很快。时间主要花在sort()上和遍历上。时间复杂度O(n*m)
/*
Wooden Sticks
Time Limit:1000MS Memory Limit:10000K
Total Submit:1278 Accepted:538
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 ( 9 , 4 ) , ( 2 , 5 ) , ( 1 , 2 ) , ( 5 , 3 ) , and ( 4 , 1 ) , then the minimum setup time should be 2 minutes since there is a sequence of pairs ( 4 , 1 ) , ( 5 , 3 ) , ( 9 , 4 ) , ( 1 , 2 ) , ( 2 , 5 ) .
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 2n 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
1
3
2 2 1 1 2 2
1
5
4 9 5 2 2 1 3 5 1 4
1
5
9 4 2 5 1 2 5 3 4 1
4 1 5 3 9 4 1 2 2 5
1
7
1 2 1 1 2 1 2 2 3 3 1 3 3 1
*/
#include "stdio.h"
#include "algorithm"
#include "vector"
using namespace std;
typedef struct
{
int l;
int w;
}wood;
bool cmp(wood c1,wood c2 )
{
if(c1.l>c2.l)
return false;
else if(c1.l==c2.l)
if(c1.w>c2.w)
return false;
else
return true;
}
int main()
{
int t,f,i,n=1,j,k,d;
wood woods[5000];
vector<wood> v[5000];
scanf("%d",&t);
while(t){
int visited[5000]={0};
scanf("%d",&f);
if(f<1||f>5000)
break;
for(i=0;i<f;i++)
{
scanf("%d %d",&woods[i].l,&woods[i].w);
if(woods[i].l<1||woods[i].l>10000||woods[i].w<1||woods[i].w>10000)
return 0;
}
sort(woods,woods+f,cmp);
j=f;
k=0;
while(j!=0){
d=f-1;
while(d!=-1&&visited[d])
d--;
if(d==-1)
break;
v[k].push_back(woods[d]);
visited[d]=1;
j--;
for (i=d;i-1>=0;i--)
{
if (v[k].back().w>=woods[i-1].w&&visited[i-1]!=1)
{
v[k].push_back(woods[i-1]);
visited[i-1]=1;
j--;
}
}
k++;
}
printf("%d\n",k);
k=1;
t--;
}
return 0;
}