贪心算法3之1001

来源:互联网 发布:2017网络自制综艺现状 编辑:程序博客网 时间:2024/04/30 11:40

1 题目编号:1001 problemB

2 题目内容:

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).
 

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
213
 

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;


}

1 0
原创粉丝点击