1. 程式人生 > >POJ 1065 Wooden Sticks【貪心】

POJ 1065 Wooden Sticks【貪心】

name right ble out max 屬性 ret sci write

題意:

有一些木棍,每個有長度和重量,要求把這些木棍排成若幹兩個屬性值均不下降的序列。問至少要分為多少個序列。且要保證排出來的子序列數最少。

思路:

( 9 , 4 ) ,( 2 , 5 ) ,( 1 , 2 ) ,( 5 , 3 ),( 4 , 1 )可以排成這樣

( 4 , 1 ) , ( 5 , 3 ) , ( 9 , 4 ); ( 1 , 2 ) , ( 2 , 5 ) .

其中:(4,1)<=(5,3)<=(9,4)為不降序列,(4,1)<(5,3)由於4<5&&1<3

(1,2)<(2,5)為不降序列。即最少的不降子序列為2,輸出2

#include<iostream>  
#include<algorithm>  
using namespace std;
const int MAX = 5001;
struct wooden{
	int l, w, flag;
}wd[MAX];
bool cmp(wooden x, wooden y){
	if (x.l != y.l) return x.l < y.l;
	return x.w < y.w;
}
int main()
{
	int T;
	cin >> T;
	while (T--)
	{
		int n;
		cin >> n;
		for (int i = 0; i < n; i++){
			cin >> wd[i].l >> wd[i].w;
			wd[i].flag = 0;
		}
		sort(wd, wd + n, cmp);
		int res = 0;
		for (int i = 0; i < n; i++){
			if (wd[i].flag)continue;
			res++;
			int cur = wd[i].w;
			for (int j = i + 1; j < n; j++){
				if (!wd[j].flag && wd[j].w >= cur){
					wd[j].flag = 1;
					cur = wd[j].w;
				}
			}
		}
		cout << res << endl;
	}
	return 0;
}

POJ 1065 Wooden Sticks【貪心】