题意:有n条木棒,给出它们每条的l和w,用一台机器对它们进行加工,如果机器正加工的木条,与在它之前加工的木块有关系:l <= l'和w <= w',则机器不用准备时间,否则需准备1分钟。问加工完全部木棒,机器最少需要准备多久。
思路:贪心。对length进行上升序列的排序,特别应注意两length相等时,应按weight的上升序列的排序。排序号之后,就是找出weight的最小上升序列数了。
代码如下:
#include<iostream>
#include<algorithm>
using namespace std;
const int Max = 5005;
struct data
{
int l, w;
bool vis;
}stick[Max];
bool cmp(data a, data b)
{
if(a.l < b.l)
return true;
if(a.l == b.l && a.w < b.w)
return true; // 应注意的a.l == b.l的情况。
return false;
}
int main()
{
int t, n, i, j;
cin >> t;
while(t--)
{
cin >> n;
for(i = 0; i < n; i ++)
{
cin >> stick[i].l >> stick[i].w;
stick[i].vis = false;
}
sort(stick, stick + n, cmp);
int ans = 0;
for(i = 0; i < n; i ++)
if(!stick[i].vis)
{
ans++;
int wei = stick[i].w; // 构造weight的上升序列。此处贪心即可
for(j = i + 1; j < n; j ++)
if(!stick[j].vis && stick[j].w >= wei)
{
stick[j].vis = true;
wei = stick[j].w;
}
}
cout << ans << endl;
}
return 0;
}