一、Problem
在一個吝嗇的國度裏有N個城市,這N個城市間只有N-1條路把這個N個城市連接起來。現在,Tom在第S號城市,他有張該國地圖,他想知道如果自己要去參觀第T號城市,必須經過的前一個城市是幾號城市(假設你不走重複的路)。
輸入
第一行輸入一個整數M表示測試數據共有M(1<=M<=5)組。
每組測試數據的第一行輸入一個正整數N(1<=N<=100000)和一個正整數S(1<=S<=100000),N表示城市的總個數,S表示參觀者所在城市的編號。
隨後的N-1行,每行有兩個正整數a,b(1<=a,b<=N),表示第a號城市和第b號城市之間有一條路連通。
輸出
每組測試數據輸N個正整數,其中,第i個數表示從S走到i號城市,必須要經過的上一個城市的編號。(其中i=S時,請輸出-1)
樣例輸入
1
10 1
1 9
1 8
8 10
10 3
8 6
1 2
10 4
9 5
3 7
樣例輸出
-1 1 10 10 9 8 3 1 1 8
二、Solution
方法一:dfs
- 使用一個 int[] pre 數組記錄每一個點的前驅即可。
- 記得拆邊…
不知道會不會超時:那個 OJ 網站進不去,有沒有大佬在評論區提供一下測評地址,萬分感謝…
我的想法是:N 很大,每次都去判斷 s 與 i 是否相連會耗時間,可以使用 List<Integer>[]
數組存邊…
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
static class Solution {
int[][] mp;
int N;
int[] pre;
void dfs(int s) {
for (int i = 1; i <= N; i++) {
if (mp[s][i] > 0 && pre[i] == 0) {
pre[i] = s;
mp[s][i] = mp[i][s] = 0;
dfs(i);
}
}
}
void init() {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int T = sc.nextInt();
while (T-- > 0) {
N = sc.nextInt();
int s = sc.nextInt();
mp = new int[N+1][N+1];
for (int i = 0; i < N-1; i++) {
int a = sc.nextInt(), b = sc.nextInt();
mp[a][b] = mp[b][a] = 1;
}
pre = new int[N+1];
pre[s] = -1;
dfs(s);
for (int i = 1; i <= N; i++) {
System.out.print(pre[i] + " ");
}
}
}
}
public static void main(String[] args) throws IOException {
Solution s = new Solution();
s.init();
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,