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;
    }
  • 相关阅读:
    多线程爬取图片(生产者-消费者模式)
    数据结构1_C---单链表的逆转
    Java基础面试知识点总结
    Java工程师必备书单
    Java工程师修炼之路(校招总结)
    Java秋招面经大合集
    我的秋招经验分享(已拿BAT头条网易滴滴)
    听说go语言越来越火了?那么请收下这一份go语言书单吧!
    2020还是AI最火?推荐几本深度学习的书籍帮你入门!
    人工智能真的有那么神秘么,推荐一份机器学习入门书单搞定它!
  • 原文地址:https://www.cnblogs.com/orion7/p/7686271.html
Copyright © 2011-2022 走看看