Files
java-contest/2/B/Main.java
2026-04-27 20:53:53 +03:00

71 lines
1.9 KiB
Java

import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String lineH = reader.readLine();
if (lineH == null)
return;
int h = Integer.parseInt(lineH.trim());
String lineW = reader.readLine();
if (lineW == null)
return;
int w = Integer.parseInt(lineW.trim());
int[] sandCounts = new int[w];
int[] stoneCounts = new int[w];
for (int i = 0; i < h; i++) {
String line = reader.readLine();
if (line == null)
break;
StringTokenizer st = new StringTokenizer(line);
for (int j = 0; j < w; j++) {
if (st.hasMoreTokens()) {
String cell = st.nextToken();
if (cell.equals("x")) {
stoneCounts[j]++;
} else if (cell.equals("0")) {
sandCounts[j]++;
}
}
}
}
for (int c = 0; c < w; c++) {
int initialStones = stoneCounts[c];
for (int k = 0; k < initialStones; k++) {
stoneCounts[c]--;
int currentHeight = sandCounts[c] + stoneCounts[c];
if (c < w - 1 && (sandCounts[c + 1] + stoneCounts[c + 1]) - currentHeight > 1 && sandCounts[c + 1] > 0) {
sandCounts[c + 1]--;
sandCounts[c]++;
} else if (c > 0 && (sandCounts[c - 1] + stoneCounts[c - 1]) - currentHeight > 1 && sandCounts[c - 1] > 0) {
sandCounts[c - 1]--;
sandCounts[c]++;
}
}
}
StringBuilder out = new StringBuilder();
for (int r = 0; r < h; r++) {
for (int c = 0; c < w; c++) {
if (r < h - sandCounts[c]) {
out.append("-");
} else {
out.append("0");
}
if (c < w - 1)
out.append(" ");
}
out.append("\n");
}
System.out.print(out);
}
}