1719๋ฒ : ํ๋ฐฐ
LV ๊ณจ๋ 3
๊ทธ๋ํ์์ ์ต๋จ ๊ฒฝ๋ก๋ฅผ ์ฐพ๋ ๋ฌธ์ ์ด๋ค.
๋ค๋ฅธ ๋ฌธ์ ์์ ์ฐจ์ด์ ์ '์ต๋จ๊ฒฝ๋ก'๋ฅผ ์ฐพ๋ ๊ฒ์ด ์๋๋ผ '์ต๋จ๊ฒฝ๋ก๋ฅผ ์ํด ์ฒซ๋ฒ์งธ๋ก ๋ฐฉ๋ฌธํด์ผ ํ๋ ๋
ธ๋'๋ฅผ ๊ตฌํด์ผ ํ๋ค๋ ๊ฒ์ด๋ค.
'์ด๋๋ฅผ ๊ฑฐ์ณค์ ๋ ๊ฐ์ฅ ๊ฐ๊น๋'๋ฅผ ๋ฌผ์ด๋ณด๋ ๋ฌธ์ ์ด๊ธฐ ๋๋ฌธ์ '์ค๊ฐ์ง์ '์ ์ก๊ณ ์ต๋จ๊ฒฝ๋ก๋ฅผ ๊ตฌํ๋ ํ๋ก์ด๋ ์์ ์๊ณ ๋ฆฌ์ฆ์ด ์ ์ ํ๋ค๊ณ ์๊ฐํ๋ค.
๊ทธ๋ ๊ฒ ์์กฐ๋กญ๊ฒ ๋ฌธ์ ๋ฅผ ํ์ด๋๊ฐ๋๋ฐ, ๋ฑ ํ๋์ ๊ฒฝ๋ก๊ฐ ์ ๋ง๋ ๊ฒ์ด๋ค...
๋จธ๋ฆฌ๋ฅผ ๋ถ์ก๊ณ ๊ณ ๋ฏผํ๋ค๊ฐ G์ ์์๊ฒ ๋ฌผ์ด๋ณด๋...
๊ฐ์ฅ ๋จผ์ ๋ฐฉ๋ฌธํด์ผ ํ๋ ๋ ธ๋๋ฅผ ๊ฐฑ์ ํ๋ ๊ณผ์ ์์ ์ค๋ฅ๊ฐ ์์๋ค.
์ฒ์์๋ ์๋์ฒ๋ผ ์์ฑ์ ํ์๋ค.
i๋ ์ค๊ฐ์ง์ ์ ์๋ฏธํ๋ค.
fBoard[from][to] = i;
๊ทธ๋ฌ๋ ์ฌ๊ธฐ์์ ์ค๊ฐ์ง์ ์ '๊ฐ์ฅ ๋จผ์ ๋ฐฉ๋ฌธํ๋ ๋ ธ๋'๋ฅผ ์๋ฏธํ์ง ์๊ธฐ ๋๋ฌธ์ ์ ๋ต์ ์ํด์๋ ์๋์ฒ๋ผ ์์ฑํด์ผ ํ๋ค.
fBoard[from][to] = fBoard[from][i];
์ด ๋ถ๋ถ๋ง ์ฃผ์ํ๋ฉด ๋๋จธ์ง๋ ์ผ๋ฐ์ ์ธ ํ๋ก์ด๋ ์์ ๊ณผ ๋์ผํ๋ค.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class backjoon_1719_ํ๋ฐฐ {
public static void main(String[] args) throws IOException {
System.setIn(new FileInputStream("src/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
// ์ด์ฐจ์ ๋ฐฐ์ด ์์ฑ
int[][] board = new int[n + 1][n + 1];
// ์ฒซ๋ฒ์งธ๋ก ๊ฑฐ์ณ๊ฐ์ผ ํ๋ ๋ถ๋ถ
int[][] fBoard = new int[n + 1][n + 1];
for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
int from = Integer.parseInt(st.nextToken());
int to = Integer.parseInt(st.nextToken());
int w = Integer.parseInt(st.nextToken());
// ์๋ฐฉํฅ ๊ฐ์
board[from][to] = w;
board[to][from] = w;
fBoard[from][to] = to;
fBoard[to][from] = from;
}
// ์ค๊ฐ ๋ค๋ฆฌ
for (int i = 1; i < n + 1; i++) {
for (int from = 1; from < n + 1; from++) {
if (from == i)
continue;
for (int to = 1; to < n + 1; to++) {
if (from == to)
continue;
// ์ฐ๊ฒฐ๋์ด ์๋ ๊ฒฝ์ฐ๋ง ๊ณ ๋ ค
if (board[from][i] > 0 && board[i][to] > 0) {
// ์ง์ ์ฐ๊ฒฐ์ด ๋์ง ์์๋ค๋ฉด ์๋ก์ด ๊ฑธ๋ก ์
๋ฐ์ดํธ
if (board[from][to] == 0) {
board[from][to] = board[from][i] + board[i][to];
//๊ฒฝ๋ก๋ฅผ ๊ฐฑ์ ํ๋ ๊ณผ์
fBoard[from][to] = fBoard[from][i];
}
// ์ง์ ๊ฐ๋ ๊ฒ๋ณด๋ค ์ค๊ฐ๋ค๋ฆฌ๋ฅผ ํตํด์ ๊ฐ๋ ๊ฒ ๋ ๋น ๋ฅด๋ค๋ฉด
else if (board[from][to] > board[from][i] + board[i][to]) {
board[from][to] = board[from][i] + board[i][to];
fBoard[from][to] = fBoard[from][i];
}
}
}
}
}
// ์ถ๋ ฅํ๊ธฐ
for (int i = 1; i < n + 1; i++) {
for (int j = 1; j < n + 1; j++) {
if (i == j) {
System.out.print("-");
} else {
System.out.print(fBoard[i][j]);
}
System.out.print(" ");
}
System.out.println();
}
System.out.println();
}
}