結構體排序-IO優化-貪心-最優值

最優值

題目

已知有NN個單詞,其排列爲P,編號從1到N。

每個單詞都有一個價值Value,該價值與單詞的首字母ch、單詞的長度LL,以及該單詞在排列中的編號ID有關。

Value = |ch| * L * ID;Value=∣ch∣∗L∗ID;  

|ch|∣ch∣ 表示字母chch對應的數字 a -> 1, b -> 2, ……, z -> 26a−>1,b−>2,……,z−>26

現在,wlxsq想知道,該如何排列這NN個單詞,使得其(NN個單詞)總價值和最大。請輸出最大價值之和。

思路

不用說,貪心。主要是輸入這裏java必須要用io優化,不然會超時,肯定是測試點的字符串太長了,奈何我不會
拿pq寫有點脫褲子放屁,但寫起來順手哈哈

代碼

import java.util.*;

public class 最優值 {
	static class word implements Comparable<word> {
		String str;
		int weight;

		public word(String str) {
			this.str = str;
			this.weight = (str.charAt(0) - 'a' + 1) * str.length();
		}

		@Override
		public int compareTo(word o) {
			return this.weight - o.weight;
		}
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		sc.nextLine();
		PriorityQueue<word> pq = new PriorityQueue<word>();
		for (int i = 0; i < n; i++) {
			pq.offer(new word(sc.nextLine()));
		}
		int count = 0;

		for (int i = 1; i <= n; i++) {
			count+=(pq.poll().weight*i);
		}
		System.out.println(count);
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章