#include <iostream> #include <algorithm> #include <utility> #include <vector> using namespace std; #define MAXN 1005 struct homework { int no; int deadline; int score; bool operator < (const homework t) const { //重载< ,扣分相同时,按提交时间递减排序 if (score == t.score) return this->deadline > t.deadline; else return this->score < t.score; //分数不同时递增排序 } }; homework H[MAXN]; int flag[MAXN] = {0}; //记录该时段是否已有作业在做,0就是空,有就存该作业编号 int findans(int n) { int i, j; int ans = 0; for (i = n-1; i >= 0; i--) { //从最后一个(扣分最多的作业)开始做 for (j = H[i].deadline; j > 0; j--) { //对照deadline,deadline前的第一个空闲做该任务 if (!flag[j]) { flag[j] = H[i].no; break; } } if (j == 0) ans += H[i].score; } return ans; } int main() { int n, time, ans; cin >> n; while (n != 0) { for (int i = 0; i < n; i++) { H[i].no = i+1; cin >> H[i].deadline; } for (int i = 0; i < n; i++) cin >> H[i].score; // 读入数据 sort(H, H + n); // 对数据进行升序排序,越靠后的数据,扣分越高,越应该先做 int res = findans(n); for (int i = 0; i < MAXN; i++) //按时间做作业顺序输出作业编号 if(flag[i]) cout << flag[i]<<' '; cout << '\n' << res << endl; fill(flag, flag + MAXN, 0); //重置flag cin >> n; } return 0; }帮我改写成Java代码
时间: 2024-01-17 13:05:15 浏览: 63
把C++代码翻译成Java代码,只需要修改一些语法即可。下面是翻译后的Java代码:
```java
import java.util.Arrays;
import java.util.Scanner;
class Main {
static class Homework implements Comparable<Homework> {
int no;
int deadline;
int score;
public Homework(int no, int deadline, int score) {
this.no = no;
this.deadline = deadline;
this.score = score;
}
@Override
public int compareTo(Homework other) {
// 重载< ,扣分相同时,按提交时间递减排序
if (score == other.score) {
return Integer.compare(other.deadline, deadline);
} else {
// 分数不同时递增排序
return Integer.compare(score, other.score);
}
}
}
static final int MAXN = 1005;
static final int[] flag = new int[MAXN];
static int findans(int n, Homework[] H) {
int ans = 0;
for (int i = n - 1; i >= 0; i--) {
// 从最后一个(扣分最多的作业)开始做
for (int j = H[i].deadline; j > 0; j--) {
// 对照deadline,deadline前的第一个空闲做该任务
if (flag[j] == 0) {
flag[j] = H[i].no;
break;
}
}
if (j == 0) {
ans += H[i].score;
}
}
return ans;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
while (n != 0) {
Homework[] H = new Homework[n];
for (int i = 0; i < n; i++) {
int deadline = scanner.nextInt();
H[i] = new Homework(i + 1, deadline, 0);
}
for (int i = 0; i < n; i++) {
H[i].score = scanner.nextInt();
}
Arrays.sort(H);
int res = findans(n, H);
for (int i = 0; i < MAXN; i++) {
// 按时间做作业顺序输出作业编号
if (flag[i] != 0) {
System.out.print(flag[i] + " ");
}
}
System.out.println("\n" + res);
Arrays.fill(flag, 0); // 重置flag
n = scanner.nextInt();
}
scanner.close();
}
}
```
阅读全文