• 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;
    }
  • 相关阅读:
    使用C#调用C++类库
    C# IntPtr类型
    C# 调用C++ dll string类型返回
    C# try、catch、finally语句
    C语言 char *、char []、const char *、string的区别与相互转换
    C# 字符串string与char数组互转!
    C#如何调用C++(进阶篇)
    Springboot通过过滤器实现对请求头的修改
    【spring事务】
    命令行参数库:McMaster.Extensions.CommandLineUtils【转】
  • 原文地址:https://www.cnblogs.com/orion7/p/7686271.html
Copyright © 2020-2023  润新知