【题目链接】
http://poj.org/problem?id=1456
题目意思
有n件物品,每件物品有个价值和最后的保质期,如果物品在保质期内卖出能拿到对应的价值。没件物品卖出要1天时间。问n件物品能拿到的最大价值。
解题思路
先贪心排序价值。高价值的先出售。而1到t时间段内空闲时间用并查集来维护。每次卖出一件时间。剩下的时间减1,直到为0(是剩下的时间,也就是fin(t))。
代码部分
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <string>
#include <map>
using namespace std;
#define LL long long
#define inf 0x3f3f3f3
const int N = 1e5+5;
int pre[N]; ///保存在0到i内还剩的空余时间
int n;
struct node ///保持价值和最后时间
{
int val,t;
}a[N];
void init() ///初始化
{
for (int i = 0; i < N; i++)
pre[i] = i;
}
bool cmp(node x,node y)
{
return x.val>y.val;
}
int fin(int x) ///查找
{
if (pre[x] != x)
pre[x] = fin(pre[x]);
return pre[x];
}
int main()
{
while (scanf("%d",&n)!=EOF)
{
init();
for (int i = 0; i < n; i++)
{
scanf("%d %d",&a[i].val,&a[i].t);
}
sort(a,a+n,cmp); ///价值排序
int sum = 0;
for (int i = 0; i < n; i++)
{
int k = fin(a[i].t);
if (k > 0) ///如果还有空闲时间
{
sum += a[i].val;
pre[k] = k-1; ///空闲时间减1;
}
}
printf("%d\n",sum);
}
}