Time Lapse :3min 4sec 1862.java12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import java.io.*;public class Main { public static int n, m, i, a, b, ans = 0; public static int[] g = new int[50001]; public static boolean[] v = new boolean[50001]; public static Reader r = new Reader(); public static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) throws Exception { n = r.nextInt(); m = r.nextInt(); for(i = 1; i <= n; ++i) g[i] = i; for(i = 0; i < m; ++i) { a = getG(r.nextInt()); b = getG(r.nextInt()); g[a] = g[b] = Math.min(a, b); } for(i = 1; i <= n; ++i) gC(i); System.out.println(ans); } public static void gC(int n) { if(v[n]) return; v[n] = true; if(g[n] != n) gC(g[n]); else ++ans; } public static int getG(int n) { return n == g[n] ? n : (g[n] = getG(g[n])); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); do { ret = (ret<<3) + (ret<<1) + (c & 0b1111); } while ((c = read()) >= '0' && c <= '9'); return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } }}