(UVA) Y2K Accounting Bug - Solution
Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1517
The solution below used Backtracking to solve this problem.
import java.io.*;
import java.util.*;
class Main {
public int s;
public int d;
public int maxSurplus;
public int[] register;
public void rec(int month, int surplus, int lastFive) {
if (month >= 5) {
if (lastFive >= 0) {
return;
}
}
if (month == 12) {
maxSurplus = Math.max(maxSurplus, surplus);
return;
}
register[month] = s;
rec(month+1, surplus+s, lastFive + s - (month >= 5 ? register[month-5] : 0));
register[month] = d;
rec(month+1, surplus+d, lastFive + d - (month >= 5 ? register[month-5] : 0));
}
public void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
while (sc.hasNext()) {
s = sc.nextInt();
d = sc.nextInt();
d *= -1;
maxSurplus = Integer.MIN_VALUE;
register = new int[12];
rec(0, 0, 0);
String answer = (maxSurplus < 0) ? "Deficit\n" : maxSurplus+"\n";
bw.write(answer);
}
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
The solution below used Backtracking to solve this problem.
import java.io.*;
import java.util.*;
class Main {
public int s;
public int d;
public int maxSurplus;
public int[] register;
public void rec(int month, int surplus, int lastFive) {
if (month >= 5) {
if (lastFive >= 0) {
return;
}
}
if (month == 12) {
maxSurplus = Math.max(maxSurplus, surplus);
return;
}
register[month] = s;
rec(month+1, surplus+s, lastFive + s - (month >= 5 ? register[month-5] : 0));
register[month] = d;
rec(month+1, surplus+d, lastFive + d - (month >= 5 ? register[month-5] : 0));
}
public void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
while (sc.hasNext()) {
s = sc.nextInt();
d = sc.nextInt();
d *= -1;
maxSurplus = Integer.MIN_VALUE;
register = new int[12];
rec(0, 0, 0);
String answer = (maxSurplus < 0) ? "Deficit\n" : maxSurplus+"\n";
bw.write(answer);
}
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
Comments
Post a Comment