这次学院天梯赛选拔赛的题目,一看题目就知道是贪心算法。开始也想到了用左右两边的差值排序来做贪心,即差值的绝对值越大的,越排在前面,然后具体求哪边就是看哪边大。当时遇到的问题是,假如都是左边大于右边呢,那右边的属性如何点满,然后就卡主了。
题目链接:http://acm.hdu.edu.cn/diy/contest_showproblem.php?pid=1008&cid=34811
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;
}