zoukankan      html  css  js  c++  java
  • 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
    ", 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
    ", ans);
        }
        return 0;
    }
    View Code
  • 相关阅读:
    模拟100 题解
    模拟99 题解
    模拟98 题解
    模拟97 题解
    模拟96 题解
    模拟95 题解
    模拟94 题解
    模拟93 题解
    模拟92 题解
    Django-- 多数据库联用
  • 原文地址:https://www.cnblogs.com/zhengguiping--9876/p/5485960.html
Copyright © 2011-2022 走看看