题目虽然长,但简单的贪心,先按单价排序,再解决问题
import java.util.Scanner;
class P2187 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int c=sc.nextInt();
while(c-->0){
double n=sc.nextInt();//money
int m=sc.nextInt();//kg
double sum=0;
int[] p=new int[m];
int[] h=new int[m];
for(int i=0;i<m;i++){
p[i]=sc.nextInt();//price
h[i]=sc.nextInt();//height
}
sort(p,h);
double canBuy=(double)n;
double kg=0;
for(int i=0;i<p.length;i++){
if(!((canBuy/p[i])<h[i])){//can buy it
kg+=h[i];
canBuy=canBuy-p[i]*h[i];
}else{
kg+=(canBuy/p[i]);
break;
}
}
System.out.printf("%.2f",kg);
System.out.println();
}
}
private static void sort(int[] p, int[] h) {
for(int i=0;i<p.length-1;i++){
for(int j=i;j<p.length;j++){
if(p[i]>p[j]){
p[i]^=p[j];
p[j]^=p[i];
p[i]^=p[j];
h[i]^=h[j];
h[j]^=h[i];
h[i]^=h[j];
}
}
}
}
private static void v(int[] a){
a[0]^=a[1];
a[1]^=a[0];
a[0]^=a[1];
}
}