zoukankan      html  css  js  c++  java
  • POJ 3111 K Best (二分)

    Demy has n jewels. Each of her jewels has some value vi and weight wi.

    Since her husband John got broke after recent financial crises, Demy has decided to sell some jewels. She has decided that she would keep k best jewels for herself. She decided to keep such jewels that their specific value is as large as possible. That is, denote the specific value of some set of jewels S = {i1, i2, …, ik} as

    .

    Demy would like to select such k jewels that their specific value is maximal possible. Help her to do so.

    Input
    The first line of the input file contains n — the number of jewels Demy got, and k — the number of jewels she would like to keep (1 ≤ k ≤ n ≤ 100 000).

    The following n lines contain two integer numbers each — vi and wi (0 ≤ vi ≤ 106, 1 ≤ wi ≤ 106, both the sum of all vi and the sum of all wi do not exceed 107).

    Output
    Output k numbers — the numbers of jewels Demy must keep. If there are several solutions, output any one.

    Sample Input
    3 2
    1 1
    1 2
    1 3
    Sample Output
    1 2

    题意:

    有n个物品的重量和价值分别是wi和vi。从中选取k个物品使得单位重量的价值最大,并输出物品的序号。

    题解:

    这种题直接贪心选取肯定是错的。应该用二分来做。

    #include<iostream>
    #include<algorithm>
    using namespace std;
    const int maxn=1e5+5;
    const double INF=1e6+5;
    int v[maxn],w[maxn];
    int n,k;
    struct node
    {
    	double y;
    	int id;
    	bool operator < (const node &p) const//重载<运算符
    	{
    		return y>p.y;
    	}
    }a[maxn];
    bool check(double x)//可以选择使得单位重量的价值不小于x
    {
    	for(int i=0;i<n;i++)
    	{
    		a[i].y=v[i]-x*w[i];
    		a[i].id=i+1;
    	}
    	sort(a,a+n);
    	double sum=0;
    	for(int i=0;i<k;i++)
    		sum+=a[i].y;
    	return sum>=0;
    }
    void solve()
    {
    	double lb=0,ub=INF;
    	for(int i=0;i<50;i++)
    	{
    		double mid=(lb+ub)/2;
    		if(check(mid))
    			lb=mid;
    		else
    			ub=mid;
    	}
    }
    int main()
    {
    	ios::sync_with_stdio(false);
    	cin>>n>>k;
    	for(int i=0;i<n;i++)
    		cin>>v[i]>>w[i];
    	solve();
    	for(int i=0;i<k;i++)
    		if(i)
    			cout<<" "<<a[i].id;
    		else
    			cout<<a[i].id;
    	cout<<endl;
    	return 0;
    }
  • 相关阅读:
    hexo命令报错
    开始使用hexo
    javascript 获取元素
    javascript DOM属性操作
    javascript DOM节点操作
    javascript 完美拖动效果
    ubuantu 18.04 LTS 版本解决网易云安装启动问题
    课后作业-阅读任务-阅读提问-3
    C# 并行循环
    C# 委托
  • 原文地址:https://www.cnblogs.com/orion7/p/7686271.html
Copyright © 2011-2022 走看看