解出题目所需最少的月数
题目链接:SDS_PRO_6_3
失败的代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class source {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int M = Integer.parseInt(st.nextToken());
int P = Integer.parseInt(st.nextToken());
int[][] cost = new int[P+1][2];
for(int i = 1;i<=P;i++){
st = new StringTokenizer(br.readLine());
cost[i] = new int[]{Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken())};
}
int solveIndex = 0;
int monthPass = 0;
int currentPay = 0;
int willPay = 0;
int leftMonty = M;
while(solveIndex!=P){
monthPass++;
if(monthPass == 1){
leftMonty = 0;
}
else{
leftMonty = M-willPay;
}
currentPay = 0;
willPay = 0;
for(int i = solveIndex+1;i<=P;i++){
currentPay+=cost[i][0];
willPay +=cost[i][1];
solveIndex++;
if(currentPay>leftMonty || willPay>M){
willPay -= cost[i][1];
solveIndex--;
break;
}
}
}
if(willPay>0){
System.out.println(monthPass+1);
}
else{
System.out.println(monthPass);
}
}
}

浙公网安备 33010602011771号