zoukankan      html  css  js  c++  java
  • 【POJ 1456】Supermarket【并查集】

    题目大意:

    题目链接:http://poj.org/problem?id=1456
    每个商品都有保质期和价值,每天只能卖出一个商品。求能卖出的最大价值。


    思路:

    这道题可以用贪心做。因为保质期前都可以卖,所以为了答案最有,就尽量将商品晚卖一些(即最后一天再卖)。就可以保证能卖出的价值最大。证明就不证了,很显而易见。
    还可以用并查集做。设father[i]father[i]表示保质期在第ii天的商品必须在第father[i]father[i]天前卖完。(因为可能第ii天卖另外一个商品,就必须推前卖),那么初始化为father[i]=1father[i]=-1,保证不会出错。


    代码:

    #include <cstdio>
    #include <algorithm>
    #include <cstring>
    #include <iostream>
    using namespace std;
    
    int n,father[10001],sum;
    
    struct node
    {
    	int day,p;  //分别表示保质期和价格
    }a[10001];
    
    bool cmp(node x,node y)
    {
    	return x.p>y.p;
    }
    
    int find(int x)  
    {
    	if (father[x]<0) return x;  //可以不用再往前了
    	return father[x]=find(father[x]);
    }
    
    int main()
    {
    	while (cin>>n)
    	{
    		memset(father,-1,sizeof(father));
    		for (int i=1;i<=n;i++)
    		 scanf("%d%d",&a[i].p,&a[i].day);
    		sort(a+1,a+1+n,cmp);  //按照价格排序
    		for (int i=1;i<=n;i++)
    		{
    			int day=find(a[i].day);  //能卖的最后一天
    			if (day>0)
    			{
    				father[day]=day-1;  //这天卖这个商品
    				sum+=a[i].p;
    			}
    		}
    		printf("%d\n",sum);
    		sum=0;
    	}
    	return 0;
    }
    
  • 相关阅读:
    ajax提交Form
    MySQL新建用户,授权,删除用户,修改密码总结
    php 数组操作类(整合 给意见)
    PHP基于数组的分页函数(核心函数array_slice())
    php生成table表格
    百度地图定位
    python-redis-订阅和发布
    宿主机-免密登录Docker容器
    docker-文件系统出错处理
    python-redis集合模式
  • 原文地址:https://www.cnblogs.com/hello-tomorrow/p/11998663.html
Copyright © 2011-2022 走看看