1 题目编号:1001 problemB
2 题目内容:
(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).
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
2 1 3
3 解题思路形成过程:此题为典型的贪心算法应用,先对木棒长度进行排序,长度相同的在对其重量进行排序即可。然后对标识flag进行判断,如果为0,则比较重量,若后者重量长度均比前者小,则flag赋值为1,并更新长度重量,同时time加1;若flag为1,则time不变。
4 感想:此题思路较简单,但一些细节应该仔细一些,同时也用了我平常不常用的flag标识判断方法
5 代码:
#include <iostream>
#include <stdlib.h>
#include<algorithm>
using namespace std;
struct stick
{
int length;
int width;
};
bool cmp(const stick &a, const stick &b)
{
if (a.length != b.length)
return(a.length >b.length);
else
return (a.width>b.width);
}
int main()
{
int T;
stick sti[5001];
int flag[5001];
cin >> T;
for (int j = 0; j < T; j++)
{
int N;
cin >> N;
int time;
int s;
for (int i = 0; i < N; i++)
{
cin >> sti[i].length >> sti[i].width;
flag[i] = 0;
}
sort(sti, sti + N, cmp);
time = 0;
for (int k = 0; k < N; k++)
{
if (flag[k])
continue;
s = sti[k].width;
for (int j = k+1; j <= N; j++)
{
if (s>=sti[j].width&&!flag[j])
{
s = sti[j].width;
flag[j] = 1;
}
}
time += 1;
}
cout << time << endl;
}
return 0;
}