poj3111 选取物品(二分+贪心)
題目傳送門
題意就是,n個物品,從中選取k個,要按照那個公式所取的值最大。
思路:最大化平均值的時候首先想到的就是二分, 我們設G(x) 為單位的重量不小于X, 我們的目標就是要找到滿足條件的最大的X, 也就是說我們的OK函數就要判斷是否能夠找到一個大小為K的集合S, 使得單位重量的價值大于等于X, 我們將當時變形轉化為vi - x*wi >= 0? 對于 所有的i 屬于集合S, 這時我們對于一個整體值vi-x*wi的值的 排序, 貪心的選取前K個, 這樣OK函數就寫好了。
但是這道題最惡心的地方是,卡常數,如果要用c++交,你的排序函數就必須 引用,g++交好像就沒關系。
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<string> #include<math.h> #include<cmath> #include<time.h> #include<map> #include<set> #include<vector> #include<queue> #include<algorithm> #include<numeric> using namespace std; typedef long long ll; const int maxn=2000010; const int INF=0x3f3f3f3f; struct dian{double v,w;double y;int id; }a[maxn]; double mps=1e10,eps=1e-9; double l,r,mid; int n,k; bool cmp(const dian& a,const dian& b){return a.y>b.y; } bool ok(double d){double e=0;for(int i=1;i<=n;i++){a[i].y=a[i].v-a[i].w*d;}sort(a+1,a+1+n,cmp);for(int i=1;i<=k;i++){e+=a[i].y;}return e>=0; } int main(){scanf("%d%d",&n,&k);for(int i=1;i<=n;i++){scanf("%lf%lf",&a[i].v,&a[i].w);a[i].id=i;}l=0,r=1e13;while(r-l>eps){mid=(l+r)/2;if(ok(mid)){l=mid;}else{r=mid;}}for(int i=1;i<=k;i++){printf("%d ",a[i].id);}printf("\n"); }K Best| Time Limit:?8000MS | ? | Memory Limit:?65536K |
| Total Submissions:?13263 | ? | Accepted:?3388 |
| Case Time Limit:?2000MS | ? | Special Judge |
Description
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 3Sample Output
1 2轉載于:https://www.cnblogs.com/mountaink/p/9536713.html
總結
以上是生活随笔為你收集整理的poj3111 选取物品(二分+贪心)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET Core IHostEn
- 下一篇: C.【转】C语言字符串与数字相互转换