这次学院天梯赛选拔赛的题目,一看题目就知道是贪心算法。开始也想到了用左右两边的差值排序来做贪心,即差值的绝对值越大的,越排在前面,然后具体求哪边就是看哪边大。当时遇到的问题是,假如都是左边大于右边呢,那右边的属性如何点满,然后就卡主了。
题目链接:http://acm.hdu.edu.cn/diy/contest_showproblem.php?pid=1008&cid=34811
RPG的天赋分支(左右两支的贪心策略)
AC代码:思路就是直接用差值排序,而不是绝对值。用右边减左边,然后求左边所有属性的和,然后对前B个,加上右边减左边的值,就是结果了

#include<bits/stdc++.h>
using namespace std;
struct tree
{
    long long int l,r; 
};
bool cmp(tree a,tree b)
{
    return (a.r-a.l)>(b.r-b.l);
}
tree tr[1000005];
int main()
{
    int t,n,a,b;
    cin>>t;
    while(t--)
    {
        cin>>n>>a>>b;
        long long int sums=0;
        for(int i=0;i<n;i++)
        {
            cin>>tr[i].l>>tr[i].r;
            sums+=tr[i].l;
        }
        sort(tr,tr+n,cmp);  
        for(int i=0;i<b;i++)
        {
            sums+=tr[i].r-tr[i].l;
        }
        cout<<sums<<endl;
    }
    return 0;
}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-09-01
  • 2021-10-08
  • 2022-02-15
  • 2022-01-01
  • 2021-11-27
  • 2021-06-22
猜你喜欢
  • 2022-12-23
  • 2021-11-26
  • 2021-09-14
  • 2021-05-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-09
相关资源
相似解决方案