#include <bits/stdc++.h> using namespace std; void solve(int w[],int n,int k){ int sum=0; int count=0; for(int i=0;i<=k;i++){ if(w[i]>n){ cout<<"No Solution"<<endl; return; } } for(int i=0;i<=k;i++){ sum+=w[i]; if(sum>n){ count++; sum=w[i]; } } cout<<count<<endl; } int main(){ int n=0; int k=0; while(cin>>n){ cin >>k; int way[k+1]; for(int i=0;i<k+1;i++){ cin>> way[i]; } solve(way,n,k); } }转java
时间: 2023-07-15 17:14:23 浏览: 98
把代码转换为 Java 可以参考下面的代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int n = scanner.nextInt();
int k = scanner.nextInt();
int[] w = new int[k + 1];
for (int i = 0; i <= k; i++) {
w[i] = scanner.nextInt();
}
solve(w, n, k);
}
scanner.close();
}
private static void solve(int[] w, int n, int k) {
int sum = 0;
int count = 0;
for (int i = 0; i <= k; i++) {
if (w[i] > n) {
System.out.println("No Solution");
return;
}
}
for (int i = 0; i <= k; i++) {
sum += w[i];
if (sum > n) {
count++;
sum = w[i];
}
}
System.out.println(count);
}
}
阅读全文