Hdu 4296 Buildings 贪心

转载:原文

  • 分析

贪心。设有两个相邻物体 a(wi,si) , b(wj,sj)。假设a在方案一中这个位置上方总w为sum,显然只有两种情况 ——a上b下或a下b上。讨论最优解:
(1)对于方案一,PDV(a)=sum-si,PDV(b)=sum+wi-sj;
(2) 对于方案二,PDV(a)=sum+wj-si,PDV(b)=sum-sj;
如果想要方案一更优的话,则要按照方案一的方式排序,则有PDV(b)<PDV(a)–> wi-si<wj-si ==——> == wi+si<wj+sj。即总和小的在上面。
选方案二同理。

//AC代码
#include <bits/stdc++.h>
using namespace std;
#define ll long long

struct node{
    ll w, s;
    bool operator<(const node &o)const{
        return w + s < o.w + o.s;
    }
}no[100005];

int main()
    {
        int n,i;
        while (cin>>n)
        {
            for (i = 0; i < n; i++)
            {
                scanf("%lld %lld", &no[i].w, &no[i].s);
            }
            sort(no,no+n);
            ll sum = no[0].w,ans=0;
            for (i = 1; i < n;sum+=no[i++].w){
                ans = max(ans, sum - no[i].s);
            }
            if(ans<0)
                ans = 0;
            printf("%lld\n", ans);
        }
        return 0;
    }

下面代码超时来着,后来把输入改成cin竟然就过了!

#include <bits/stdc++.h>
using namespace std;

struct node{
    int w, s;
    bool operator<(const node &o)const{
        return w + s < o.w + o.s;
    }
}no[100010];

int main()
    {
        int n;
        while (scanf("%d", &n))
        {
            for (int i = 0; i < n;i++){
                scanf("%d %d", &no[i].w, &no[i].s);
            }
            sort(no,no+n);
            long long sum = 0, max = -1,value;
            for (int i = 0; i < n;i++){
                value = sum - no[i].s;
                sum+=no[i].w;
                if(max<value)
                    max = value;
            }
            if(max<0)
                max = 0;
            printf("%lld\n", max);
        }
        return 0;
    }
/*
3
10 6
2 3
5 4
2
2 2
2 2
3
10 3
2 5
3 3 

1
0
2
 */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值