您的位置:首页 > 其它

51nod 1257 背包问题 V3(二分)

2016-09-21 01:01 281 查看
思路:二分答案然后判一判就可以了

#include<bits/stdc++.h>
using namespace std;
const int maxn = 50000+7;
#define LL long long
LL gcd(LL a,LL b){return b==0?a:gcd(b,a%b);}
int n,k;
struct Node
{
int w,p;
double rate;
}beg[maxn];
bool cmp(Node a,Node b){return a.rate>b.rate;}
int resw,resp;
int answ,ansp;
bool check(double p)
{
resw=0;
resp=0;
double mark=0.0;
for(int i = 1;i<=n;i++)
beg[i].rate = 1.0*beg[i].p-beg[i].w*p;
sort(beg+1,beg+1+n,cmp);
for(int i = 1;i<=k;i++)
{
resw+=beg[i].w;
resp+=beg[i].p;
mark+=beg[i].rate;
}
if(mark>=0)return true;
return false;
}
int main()
{
scanf("%d%d",&n,&k);
for(int i = 1;i<=n;i++)
scanf("%d%d",&beg[i].w,&beg[i].p);
double l = 0.0,r=50000;
for(int i = 0;i<=100;i++)
{
double mid = (l+r)/2;
if(check(mid))
{
answ=resw;
ansp=resp;
l=mid;
}
else
r=mid;
}
LL gg = gcd(answ,ansp);
answ/=gg;
ansp/=gg;
printf("%d/%d\n",ansp,answ);
}


1257 背包问题 V3


基准时间限制:3 秒 空间限制:131072 KB 分值: 80 难度:5级算法题


 收藏


 关注

N个物品的体积为W1,W2......Wn(Wi为整数),与之相对应的价值为P1,P2......Pn(Pi为整数),从中选出K件物品(K <= N),使得单位体积的价值最大。

Input
第1行:包括2个数N, K(1 <= K <= N <= 50000)
第2 - N + 1行:每行2个数Wi, Pi(1 <= Wi, Pi <= 50000)


Output
输出单位体积的价值(用约分后的分数表示)。


Input示例
3 2
2 2
5 3
2 1


Output示例
3/4
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: