有N个任务,每个任务有一个最晚结束时间以及一个对应的奖励。在结束时间之前完成该任务,就可以获得对应的奖励。完成每一个任务所需的时间都是1个单位时间。有时候完成所有任务是不可能的,因为时间上可能会有冲突,这需要你来取舍。求能够获得的最高奖励。
Input
第1行:一个数N,表示任务的数量(2 <= N <= 50000) 第2 - N + 1行,每行2个数,中间用空格分隔,表示任务的最晚结束时间E[i]以及对应的奖励W[i]。(1 <= E[i] <= 10^9,1 <= W[i] <= 10^9)
Output
输出能够获得的最高奖励。
Input示例
7 4 20 2 60 4 70 3 40 1 30 4 50 6 10
Output示例
230
大暴力(500ms)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=50000+100;
struct node
{
int end;
ll cost;
} a[maxn];
bool cmp(node x,node y)
{
if(x.cost>y.cost) return true;
return false;
}
int book[maxn];
int main()
{
int n,i,j,k;
ll ans;
ans=0;
cin>>n;
for(i=0;i<n;i++) cin>>a[i].end>>a[i].cost;
sort(a,a+n,cmp);
for(i=0;i<n;i++) {
k=a[i].end;
while(k) {
if(book[k]==0) {
book[k]=1;
ans+=a[i].cost;
break;
}
k--;
}
}
cout<<ans<<endl;
return 0;
}
为了提高匹配的效率,有两种方案,一是二分查找,二是用并查集;;
并查集的查找为
int find(int x)
{
if(x<=0) return -1;
if(x==f[x]) return f[x]=x-1;
else return f[x]=find(f[x]);
}
二分查找为:
k=a[i].end;
it=book.lower_bound(k);
if(it==book.end()) continue;
ans+=a[i].cost;
book.erase(*it);
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<set>
using namespace std;
typedef long long ll;
const int maxn=50000+100;
struct node
{
int end;
ll cost;
} a[maxn];
bool cmp(node x,node y)
{
if(x.cost>y.cost) return true;
return false;
}
set<int>book;
set<int>::iterator it;
int main()
{
ios::sync_with_stdio(false);
int n,i,j,k,t;
ll ans;
ans=0;
cin>>n;
for(i=0;i<n;i++) {
cin>>a[i].end>>a[i].cost;
a[i].end=min(a[i].end,n);
a[i].end=-a[i].end;
book.insert(-i-1);
}
sort(a,a+n,cmp);
for(i=0;i<n;i++) {
k=a[i].end;
it=book.lower_bound(k);
if(it==book.end()) continue;
ans+=a[i].cost;
book.erase(*it);
}
cout<<ans<<endl;
return 0;
}