(SPOJ) Fechadura - Solution
Link to the problem: http://br.spoj.com/problems/FECHAD14/
The solution below used Greedy algorithm to solve this problem. Starting from the left, we increase or decrease the height of pin n and pin n+1. We only move forward when pin n has the desired height.
import java.io.*;
import java.util.*;
class Main {
public void process() throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
String[] s = line.split("\\s");
int numPins = Integer.parseInt(s[0]);
int height = Integer.parseInt(s[1]);
line = br.readLine();
s = line.split("\\s");
int[] pins = new int[numPins];
for (int i = 0; i < numPins; i++) {
pins[i] = Integer.parseInt(s[i]);
}
int count = 0;
for (int i = 0; i < numPins-1; i++) {
while (pins[i] != height) {
if (pins[i] < height) {
pins[i]++;
pins[i+1]++;
}
else {
pins[i]--;
pins[i+1]--;
}
count++;
}
}
System.out.println(count);
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
The solution below used Greedy algorithm to solve this problem. Starting from the left, we increase or decrease the height of pin n and pin n+1. We only move forward when pin n has the desired height.
import java.io.*;
import java.util.*;
class Main {
public void process() throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
String[] s = line.split("\\s");
int numPins = Integer.parseInt(s[0]);
int height = Integer.parseInt(s[1]);
line = br.readLine();
s = line.split("\\s");
int[] pins = new int[numPins];
for (int i = 0; i < numPins; i++) {
pins[i] = Integer.parseInt(s[i]);
}
int count = 0;
for (int i = 0; i < numPins-1; i++) {
while (pins[i] != height) {
if (pins[i] < height) {
pins[i]++;
pins[i+1]++;
}
else {
pins[i]--;
pins[i+1]--;
}
count++;
}
}
System.out.println(count);
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
Comments
Post a Comment