Supermarket---poj456(贪心并查集优化)

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

题意是现有n个物品,每个物品有一个保质期和一个利润,现在每天只能卖一个商品,问最大的利润是多少,商品如果过期了就不能卖了;

暴力的方法:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <map>
#include <vector>
using namespace std;
typedef long long LL;
#define PI 4*atan(1.0)
#define N 10550
#define met(a, b) memset(a, b, sizeof(a))

struct node
{
    int p, d;
}a[N];
int cmp(node p, node q)
{
    if(p.p != q.p)
        return p.p > q.p;
    return p.d > q.d;
}
int vis[N];

int main()
{
    int n;
    while(scanf("%d", &n)!=EOF)
    {
        met(vis, 0);
        met(a, 0);

        for(int i=1; i<=n; i++)
            scanf("%d %d", &a[i].p, &a[i].d);

        sort(a+1, a+n+1, cmp);

        int ans = 0;
        for(int i=1; i<=n; i++)
        {
            for(int j=a[i].d; j>=1; j--)
            {
                if(!vis[j])
                {
                    ans+=a[i].p;
                    vis[j] = 1;
                    break;
                }
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}
View Code

 

并查集优化:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <map>
#include <vector>
using namespace std;
typedef long long LL;
#define PI 4*atan(1.0)
#define N 10500
#define met(a, b) memset(a, b, sizeof(a))

struct node
{
    int p, d;
}a[N];
int cmp(node p, node q)
{
    if(p.p != q.p)
        return p.p > q.p;
    return p.d > q.d;
}

int f[N];
int Find(int x)
{
    if(f[x]!=x)
        f[x] = Find(f[x]);
    return f[x];
}

int main()
{
    int n;
    while(scanf("%d", &n)!=EOF)
    {
        for(int i=0; i<N; i++)
            f[i] = i;
        met(a, 0);

        for(int i=1; i<=n; i++)
            scanf("%d %d", &a[i].p, &a[i].d);

        sort(a+1, a+n+1, cmp);

        int ans = 0;
        for(int i=1; i<=n; i++)
        {
            int t = Find(a[i].d);
            if(t > 0)
            {
                ans += a[i].p;
                f[t] = t-1;
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}
View Code

 

posted @ 2016-05-12 15:49  西瓜不懂柠檬的酸  Views(179)  Comments(0Edit  收藏  举报
levels of contents