题目大意:给定一些物品以及他们的价值和时间w、t,表示物品在时间t内售出能得到w 的价值,一天只能出售一件物品,求最大利润;
非常有意思的一道并查集的思想题
首先以价值为关键字排序,类似于贪心的思想,然后以时间作为维度来构建并查集;
以最后期限作为根节点建立并查集,每次找到一个未被占用的时间,就把他加入并查集中,并把他连接到前一个为被占用的时间里,直到找到根节点(第一天)。
偷懒没打路径压缩(逃
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
template<class T>void read(T &x)
{
x=0;char ch=getchar();
while(ch<'0'||ch>'9') ch=getchar();
while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
}
struct yhh{
int w,t;
}a[10007];
int fa[10007],ans,father,n;
int find(int x)
{
while(fa[x]!=-1) x=fa[x];
return x;
}
bool cmp(yhh x,yhh y)
{
return x.w>y.w;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
memset(fa,-1,sizeof(fa));
for(int i=1;i<=n;++i) read(a[i].w),read(a[i].t);
ans=0;
sort(a+1,a+n+1,cmp);
for(int i=1;i<=n;++i)
{
father=find(a[i].t);
if(father>0)
{
ans+=a[i].w;
fa[father]=father-1;
}
}
printf("%d\n",ans);
}
return 0;
}