ACM Problem 1001(棍棒问题)
(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).
#include<iostream>
using namespace std;
#include <vector>
#include <algorithm>
#include<string.h>
struct stick
{
int l;
int w;
};
bool use[5010];
bool com_s(const stick s1,const stick s2)
{
if(s1.l != s2.l)
return s1.l < s2.l;
else
return s1.w < s2.w;
}
int choose(vector<stick> & v1,int time)
{
int num = v1.size();
memset(use,0,sizeof(use));
for(int i = 0;i < num;i++)
{
stick big = v1[i];
if(!use[i])
{
for(int j = i+1;j < num;j++)
{
if(v1[j].w >= big.w&&!use[j])
{
use[j] = true;
big = v1[j];
}
}
time++;
}
}
return time;
}
int main()
{
vector<stick> v1;
int t = 0;
int num = 0;
cin >> t;
while(t--)
{
cin >> num;
stick * s1 = new stick[num];
int time = 0;
for(int i = 0;i < num;i++)
{
cin >> s1[i].l >> s1[i].w;
use[i] = false;
v1.push_back(s1[i]);
}
sort(v1.begin(),v1.end(),com_s);
time = choose(v1,time);
cout << time << endl;
v1.clear();
delete []s1;
}
}
思路:首先定义一个棍棒的结构体,然后先按照棍棒长度升序排序,如果长度相同,再按照重量升序排序。用一个数组记录所有棍棒的状态,1代表用过的,0代表还没用过,然后每次比较后,符合后面长度和重量大于前面的长度和重量的棍棒,让其表示为1,因为所需要的时间最多为棍棒的数量,所以每个每个没用过的棍棒比较的次数为棍棒的数量,直到所有棍棒状态变为1。