(UVA) Command War - Solution
Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=2829
First, we need to sort the entries according to the time a soldier need to complete a job. Then, the soldiers are chosen from those who need more time to complete a job to those who need less time.
import java.io.*;
import java.util.*;
class Main {
public static void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
int numCase = 0;
int numSoldiers = sc.nextInt();
while (numSoldiers != 0) {
Soldier[] soldiers = new Soldier[numSoldiers];
for (int i = 0; i < numSoldiers; i++) {
int brief = sc.nextInt();
int execTime = sc.nextInt();
soldiers[i] = new Soldier(brief, execTime);
}
Arrays.sort(soldiers);
int sumTime = 0;
int maxTime = 0;
for (int i = 0; i < numSoldiers; i++) {
sumTime += soldiers[i].brief;
maxTime = Math.max(maxTime, sumTime+soldiers[i].execTime);
}
System.out.println("Case " + ++numCase + ": " + maxTime);
numSoldiers = sc.nextInt();
}
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
class Soldier implements Comparable<Soldier> {
int brief;
int execTime;
public Soldier(int b, int eT) {
brief = b;
execTime = eT;
}
public int compareTo(Soldier s) {
return s.execTime-this.execTime;
}
}
First, we need to sort the entries according to the time a soldier need to complete a job. Then, the soldiers are chosen from those who need more time to complete a job to those who need less time.
import java.io.*;
import java.util.*;
class Main {
public static void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
int numCase = 0;
int numSoldiers = sc.nextInt();
while (numSoldiers != 0) {
Soldier[] soldiers = new Soldier[numSoldiers];
for (int i = 0; i < numSoldiers; i++) {
int brief = sc.nextInt();
int execTime = sc.nextInt();
soldiers[i] = new Soldier(brief, execTime);
}
Arrays.sort(soldiers);
int sumTime = 0;
int maxTime = 0;
for (int i = 0; i < numSoldiers; i++) {
sumTime += soldiers[i].brief;
maxTime = Math.max(maxTime, sumTime+soldiers[i].execTime);
}
System.out.println("Case " + ++numCase + ": " + maxTime);
numSoldiers = sc.nextInt();
}
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
class Soldier implements Comparable<Soldier> {
int brief;
int execTime;
public Soldier(int b, int eT) {
brief = b;
execTime = eT;
}
public int compareTo(Soldier s) {
return s.execTime-this.execTime;
}
}
Comments
Post a Comment