小v今年有n門課,每門都有考試,爲了拿到獎學金,小v必須讓自己的平均成績至少爲avg。每門課由平時成績和考試成績組成,滿分爲r。現在他知道每門課的平時成績爲ai ,若想讓這門課的考試成績多拿一分的話,小v要花bi 的時間複習,不復習的話當然就是0分。同時我們顯然可以發現複習得再多也不會拿到超過滿分的分數。爲了拿到獎學金,小v至少要花多少時間複習。
輸入描述:
第一行三個整數n,r,avg(n大於等於1小於等於1e5,r大於等於1小於等於1e9,avg大於等於1小於等於1e6),接下來n行,每行兩個整數ai和bi,均小於等於1e6大於等於1
輸出描述:
一行輸出答案。
輸入例子:
5 10 9 0 5 9 1 8 1 0 1 9 100
輸出例子:
43
分析:解題思路是依次求出每門課成績增長一分的最小時間代價,然後根據最小時間代價從小到大依次去複習,直至該門課滿分。
JAVA實現該數據結構的話利用原生的結構比較困難,只有自己構造類,同時自定義比較器。因爲要至少要保存當前已得到分數和時間代價,同時還有保持程序中的這一對數據是有序排列。
代碼如下:
import java.util.Scanner;
import java.util.Arrays;
class Score implements Comparable<Score>{
private int score;
private int time;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
@Override
public int compareTo(Score o) {
if(this.time>o.time) return 1;
else if(this.time==o.time) return 0;
else return -1;
}
public Score(int score, int time) {
super();
this.score = score;
this.time = time;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNextInt()){
int n=sc.nextInt();
int r=sc.nextInt();
int avg=sc.nextInt();
int init=n*avg;//總的平均值
long result=0;//所需時間,最後的結果可能超過了int數據
Score[] score=new Score[n];
for (int i = 0; i < n; i++) {
score[i]=new Score(sc.nextInt(), sc.nextInt());
init-=score[i].getScore();
}//數據初始化完畢
Arrays.sort(score);//排序完畢
for (int i = 0; i < n; i++) {
if(init>0){
if(r-score[i].getScore()<init){
result+=(r-score[i].getScore())*score[i].getTime();
init-=(r-score[i].getScore());
}else{
result+=init*score[i].getTime();
init=0;//結束
}
}else{
break;
}
}
//先去學價值最好的課程,學滿爲止
System.out.println(result);
}
}
}
在測試的時候,最後的大數據結果始終提示沒通過,仔細檢查了下,結果result是int,可能不夠保存,故換爲long.