小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.