poj 1456 Supermarket 贪心 并查集优化

按价值排序后由大到小加进结果,贪心的放在最后的时间里如果某个时间已经占满往前放这时要用并查集维护这天前面没有占满的最后一天

#include
#include
#include
#include
#include
#define maxn 10015
using namespace std;
int n;
struct node{
    int mo,ti;
}no[maxn];
int fa[maxn];
int getFa(int pre)
{
    if(pre == fa[pre])return pre;
    fa[pre] = getFa(fa[pre]);
    return fa[pre];
}
bool cmp(node no1,node no2)
{
    return no1.mo>no2.mo;
}
int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        int time = -1;
        for(int i=1;i<=n;i++){ scanf("%d %d",&no[i].mo,&no[i].ti); time = max(time,no[i].ti);}
        sort(no+1,no+n+1,cmp);
        for(int i=0;i<=time;i++)fa[i] = i;
        int sum = 0;
        for(int i=1;i<=n;i++)
        {
            int pre = getFa(no[i].ti);
            if(pre)
            {
               fa[pre] = pre-1;
               sum+=no[i].mo;
            }
        }
        printf("%d\n",sum);
    }
    return 0;
}

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