-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathURI1162TrainSwapping.java
More file actions
68 lines (57 loc) · 1.78 KB
/
URI1162TrainSwapping.java
File metadata and controls
68 lines (57 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
/**
* See
* <a href="https://www.urionlinejudge.com.br/judge/en/problems/view/1162">Train
* Swapping</a>
*
* @author Brian Yeicol Restrepo Tangarife
*/
public class URI1162TrainSwapping {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
int N = readInt();
int L, swaps;
String[] P;
while (N-- > 0) {
L = readInt();
int[] positions = new int[L];
P = read().split("\\s");
for (int i = 0; i < L; i++) {
positions[i] = Integer.parseInt(P[i]);
}
swaps = bubbleSort(positions);
out.println("Optimal train swapping takes " + swaps + " swaps.");
}
out.close();
}
private static String read() throws IOException {
return in.readLine();
}
private static int readInt() throws IOException {
return Integer.parseInt(in.readLine());
}
private static int bubbleSort(int[] array) {
int totalSwaps = 0;
int length = array.length;
for (int i = 0; i < length; i++) {
int swaps = 0;
for (int j = 0; j < length - 1; j++) {
if (array[j] > array[j + 1]) {
int tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
swaps++;
totalSwaps++;
}
}
if (swaps == 0) {
return totalSwaps;
}
}
return totalSwaps;
}
}