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.
2 1 3
将n根木头放入一台机器加工,若要放的木头的长度与宽度都分别大于或等于上一根的长度与宽度,则需要调整机器。第一根放之前也需要调整机器。求需要调整几次
贪心问题。贪心标准为一次调整加工的木头尽可能的多。因此需要第一根木头尽可能的小,然后找出所有与它相容的木头。所求调整次数即为最优解。
下面的代码使用了数组(使用容器会方便一些,当时有些偷懒。。。。)先由小到大sort,从第一个开始,每当找到上一个相容的即从数组中除去(重新赋值为-1,使数据无效)寻找到最末,然后从下一个有效数据开始重复以上过程,知道数组中全为无效数据,执行此过程的次数即为解。
#include<iostream>#include<algorithm>#include<stdio.h>using namespace std;struct woods{int l;int w;}a[5000];bool cmp(woods a, woods b){if (a.l < b.l)return 1;else if (a.l == b.l){if (a.w < b.w)return 1;}return 0;}int main(){//freopen("date.in", "r", stdin);//freopen("date.out", "w", stdout);int N,m,sum,flag,count;cin >> N;woods tem;for (int i = 0; i < N; i++){sum = 0;flag = 1;cin >> m;for (int j = 0; j < m; j++){cin >> a[j].l >>a[j].w;}sort(a, a+m, cmp);/*for (int l = 0; l < m; l++){cout << a[l].l << " " << a[l].w << endl;}*/for (int k = 0; k < m ; k++){//count = 0;tem.l = a[k].l;tem.w = a[k].w;if (a[k].l != -1){sum++;for (int l = k; l < m; l++){if (a[l].l >= tem.l&&a[l].w >= tem.w){tem.l = a[l].l;tem.w = a[l].w;a[l].l = -1;a[l].w = -1;//count++;}}}}cout << sum<<endl;}}
原文:http://www.cnblogs.com/liuzhanshan/p/5331373.html