⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pku3111_kbest_2.java

📁 这是本人对K-BEST的算法编的代码,希望对大家有所帮助
💻 JAVA
字号:
/**
 * Pku3111 - K Best 
 Time Limit:8000MS  Memory Limit:65536K
 Total Submit:244 Accepted:28 Special Judged 
 Case Time Limit:2000MS 

 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 3

 Sample Output


 1 2

 Source
 Northeastern Europe 2005, Northern Subregion

 */

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

/**
 * @author nyz
 * @version 0.9 06/11/30
 */
public class Pku3111_KBest_2 {

	static public class Jew {
		public int v, w, idx;
	};

	static private double s;

	static public void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		
		double st;
		long V, W;
		while (scan.hasNext()) {
			int n = scan.nextInt();
			int k = scan.nextInt();

			Jew[] jews = new Jew[n];

			for (int i = 0; i < n; i++) {
				jews[i]=new Jew();
				jews[i].v = scan.nextInt();
				jews[i].w = scan.nextInt();
				jews[i].idx = i + 1;
			}
			
			s = 1.0;
			st = 0.0;
			while (Math.abs(s - st) >0) {
				s = st;
				Arrays.sort(jews, new Comparator<Jew>() {
					public int compare(Jew j1, Jew j2) {
						return (int) -Math.signum((j1.v - s * j1.w) - (j2.v - s * j2.w));
					}
				});

				V = 0;
				W = 0;
				for (int i = 0; i < k; i++) {
					V += jews[i].v;
					W += jews[i].w;
				}
				st = (double) V / (double) W;
			}

			for (int i = 0; i < k; i++) {
				System.out.print(jews[i].idx + " ");
			}
			System.out.println();

		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -