Supermarket 并查集或贪心

题目链接:http://poj.org/problem?id=1456

题目大意:给你n个物品,每种物品都有一个价值v和最晚出售时间t,问你怎样的顺序出售可获得最大利润?

首先说贪心法:把物品按价值降序排序,然后从开始遍历物品,如果这个物品在最晚期限那天可以出售,就在那天出售,并标记这天有物品出售,如果那天已经有物品出售,就向前找能出售的第一个时间,标记,当找不到能出售的时间,则这个物品不能出售(因为这个物品能出售的时间肯定被比他价值大的物品占用了),当然这种决策也保证了可以出售总价值最大的物品,代码如下:

#include
#include
#include
using namespace std;
#define N 10005
bool hash[N];
struct node{int v;int t;}s[N];
bool cmp(node x,node y)
{
    return x.v>y.v;//降序排列
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        memset(hash,true,sizeof(hash));
        for(int i=0;i0;j--)
                    if(hash[j]) {hash[j]=false;sum+=s[i].v;break;}
            }
        }
        printf("%d\n",sum);
    }
}

当然,你们会发现上面的代码查找 可以出售的时间 花了很多时间,这个题也可以用并查集,查找速度当然比这个查找要快,解释在代码里,代码如下:

#include
#include
#include
using namespace std;
#define N 10005
struct node{int v;int t;}s[N];
int fa[N];
bool cmp(node x,node y)
{
    return x.v>y.v;
}
int find(int x)
{
    if(x==fa[x]) return x;
    return fa[x]=find(fa[x]);//此处边查找边更新;
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        for(int i=1;i0)//如果当前天数前有可用天数
            {
                sum+=s[i].v;
                fa[fx]=fx-1;//把当前 可用天数-1赋给其父节点
            }
        }
        printf("%d\n",sum);
    }
}



 

你可能感兴趣的:(并查集)