結果
問題 | No.1254 補強への架け橋 |
ユーザー |
![]() |
提出日時 | 2022-08-16 11:25:15 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 974 ms / 2,000 ms |
コード長 | 3,581 bytes |
コンパイル時間 | 2,396 ms |
コンパイル使用メモリ | 80,120 KB |
実行使用メモリ | 108,004 KB |
最終ジャッジ日時 | 2024-10-03 03:29:30 |
合計ジャッジ時間 | 41,236 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 123 |
ソースコード
import java.io.*;import java.util.*;public class Main {static ArrayList<HashMap<Integer, Integer>> graph = new ArrayList<>();static int[] depths;static int[] parents;public static void main(String[] args) throws Exception {Scanner sc = new Scanner();int n = sc.nextInt();ArrayList<Integer> ans = new ArrayList<>();for (int i = 0; i < n; i++) {graph.add(new HashMap<>());}UnionFindTree uft = new UnionFindTree(n);int orgA = 0;int orgB = 0;for (int i = 1; i <= n; i++) {int left = sc.nextInt() - 1;int right = sc.nextInt() - 1;if (uft.same(left, right)) {ans.add(i);orgA = left;orgB = right;} else {uft.unite(left, right);graph.get(left).put(right, i);graph.get(right).put(left, i);}}depths = new int[n];parents = new int[n];setDepth(0, 0, 0);setAns(orgA, orgB, ans);StringBuilder sb = new StringBuilder();sb.append(ans.size()).append("\n");for (int i = 0; i < ans.size(); i++) {if (i > 0) {sb.append(" ");}sb.append(ans.get(i));}System.out.println(sb);}static void setAns(int left, int right, ArrayList<Integer> ans) {if (depths[left] < depths[right]) {setAns(right, left, ans);return;}while (depths[left] > depths[right]) {ans.add(graph.get(left).get(parents[left]));left = parents[left];}while (left != right) {ans.add(graph.get(left).get(parents[left]));left = parents[left];ans.add(graph.get(right).get(parents[right]));right = parents[right];}}static void setDepth(int idx, int p, int d) {depths[idx] = d;parents[idx] = p;for (int x : graph.get(idx).keySet()) {if (x == p) {continue;}setDepth(x, idx, d + 1);}}static class UnionFindTree {int[] parents;public UnionFindTree(int size) {parents = new int[size];for (int i = 0; i < size; i++) {parents[i] = i;}}public int find(int x) {if (x == parents[x]) {return x;} else {return parents[x] = find(parents[x]);}}public boolean same(int x, int y) {return find(x) == find(y);}public void unite(int x, int y) {parents[find(x)] = find(y);}}}class Scanner {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));StringTokenizer st = new StringTokenizer("");public Scanner() throws Exception {}public int nextInt() throws Exception {return Integer.parseInt(next());}public long nextLong() throws Exception {return Long.parseLong(next());}public double nextDouble() throws Exception {return Double.parseDouble(next());}public String next() throws Exception {while (!st.hasMoreTokens()) {st = new StringTokenizer(br.readLine());}return st.nextToken();}}