|
| 1 | +```java |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | +import java.io.*; |
| 5 | + |
| 6 | +class Main { |
| 7 | + |
| 8 | + // IO field |
| 9 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 10 | + static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 11 | + static StringTokenizer st; |
| 12 | + |
| 13 | + static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());} |
| 14 | + static int nextInt() {return Integer.parseInt(st.nextToken());} |
| 15 | + static long nextLong() {return Long.parseLong(st.nextToken());} |
| 16 | + static void bwEnd() throws Exception {bw.flush();bw.close();} |
| 17 | + |
| 18 | + // Additional field |
| 19 | + |
| 20 | + static List<Integer>[] V; |
| 21 | + static int N; |
| 22 | + static int[] A, B; |
| 23 | + static boolean[] vis; |
| 24 | + static int ans = 0, cnt = 0; |
| 25 | + static boolean multiedge; |
| 26 | + |
| 27 | + public static void main(String[] args) throws Exception { |
| 28 | + |
| 29 | + ready(); |
| 30 | + solve(); |
| 31 | + |
| 32 | + bwEnd(); |
| 33 | + |
| 34 | + } |
| 35 | + |
| 36 | + static void ready() throws Exception{ |
| 37 | + |
| 38 | + N = Integer.parseInt(br.readLine()); |
| 39 | + A = new int[N]; |
| 40 | + B = new int[N]; |
| 41 | + |
| 42 | + nextLine(); |
| 43 | + for(int i=0;i<N;i++) A[i] = nextInt(); |
| 44 | + |
| 45 | + nextLine(); |
| 46 | + for(int i=0;i<N;i++) B[i] = nextInt(); |
| 47 | + |
| 48 | + vis = new boolean[1000001]; |
| 49 | + V = new List[1000001]; |
| 50 | + |
| 51 | + for(int i=0;i<=1000000;i++) V[i] = new ArrayList<>(); |
| 52 | + |
| 53 | + for(int i=0;i<N;i++) { |
| 54 | + V[A[i]].add(B[i]); |
| 55 | + V[B[i]].add(A[i]); |
| 56 | + } |
| 57 | + |
| 58 | + for(int i=0;i<=1000000;i++) if(!V[i].isEmpty()) Collections.sort(V[i]); |
| 59 | + |
| 60 | + } |
| 61 | + |
| 62 | + static void solve() throws Exception{ |
| 63 | + |
| 64 | + for(int i=0;i<=1000000;i++) { |
| 65 | + if(vis[i]) continue; |
| 66 | + multiedge = false; |
| 67 | + cnt = 0; |
| 68 | + vis[i] = true; |
| 69 | + if(dfs(i, -1) && !multiedge) ans += cnt-1; |
| 70 | + else ans += cnt; |
| 71 | + } |
| 72 | + bw.write(ans + "\n"); |
| 73 | + |
| 74 | + } |
| 75 | + |
| 76 | + // 트리면 true, 아니면 false |
| 77 | + static boolean dfs(int n, int p) { |
| 78 | + cnt++; |
| 79 | + boolean res = true; |
| 80 | + int prev = -1; |
| 81 | + for(int i=0;i<V[n].size();i++) if(!V[n].get(i).equals(p)) { |
| 82 | + int x = V[n].get(i); |
| 83 | + if(i < V[n].size()-1 && V[n].get(i+1).equals(x)) multiedge = true; |
| 84 | + if(vis[x]) res = false; |
| 85 | + else{ |
| 86 | + vis[x] = true; |
| 87 | + res &= dfs(x,n); |
| 88 | + } |
| 89 | + } |
| 90 | + return res; |
| 91 | + } |
| 92 | + |
| 93 | + |
| 94 | +} |
| 95 | + |
| 96 | +``` |
0 commit comments