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
Output
Input示例
Output示例
#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
相关文章推荐
- 51nod 1257 背包问题V3
- [51nod] 1257 背包问题 V3
- 51nod 1257 背包问题 V3
- 51nod 1257 背包问题 V3(分数规划)
- 51Nod-1257-背包问题 V3
- 51nod 1257 背包问题 V3
- 51 nod oj 1257 背包问题 V3【01分数规划】
- 1257 背包问题 V3——分数规划
- 二分查找,背包问题v3
- 51nod-【多重背包问题】
- 51nod 1086 背包问题V2(巧妙拆分多重背包)
- 51Nod 有限背包计数问题 题解报告
- 51nod 1085 背包问题
- 51nod-0-1背包问题
- 51nod 1086 背包问题 V2(多重背包)
- 51nod 1085 背包问题【01背包】
- 51NOD 背包问题v2(动态规划)
- 【51Nod 1086】背包问题 V2
- 51nod-1086 背包问题(多重背包)
- 51nod 1086 背包问题 V2 多重背包