基准时间限制: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
嗯,其实就要精确到分数就是了,在原来精确到小数的基础上记录一些量就可以了。
代码:
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#define N 50005
#define INF 0x3f3f3f3f
#define maxn 10005
#define maxx 50005
typedef long long ll;
using namespace std;
int n,k;
double eps=1e-8;
double mid;
struct node
{
int w,p;
}a[50005];
bool cmp(node x,node y)
{
return x.p-mid*x.w>y.p-mid*y.w;
}
ll gcd(ll a,ll b)
{
return a%b==0?b:gcd(b,a%b);
}
int main()
{
cin>>n>>k;
double l=0,r=0;
for(int i=0;i<n;i++)
{
scanf("%d%d",&a[i].w,&a[i].p);
r=max(r,(double)a[i].p/a[i].w);
}
ll ans1,ans2;
double _max=0;
while(r-l>=eps)
{
mid=(l+r)/2;
sort(a,a+n,cmp);
ll _w=0;
ll _p=0;
double sum=0;
for(int i=0;i<k;i++)
{
sum+=a[i].p-mid*a[i].w;
_w+=a[i].w;
_p+=a[i].p;
}
if(sum<eps)r=mid;
else
{
ans1=_p;
ans2=_w;
l=mid;
}
}
ll g=gcd(ans1,ans2);
cout<<(ans1/g)<<"/"<<(ans2/g)<<endl;
return 0;
}