import java.util.*; //并查集 class UF { //父节点数组 int[] parent; //初始连通分量个数 int count; public UF(int n) { parent = new int[n]; count = n; //把父节点设置为自己 for (int i = 0; i < n; i++) { parent[i] = i; } } //递归找到父节点 public int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } //p为想要连接的父节点 q为源节点 public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; parent[rootQ] = rootP; count--; } //判断两个节点是否构成连通分量 public boolean isconnect(int p, int q) { return find(p) == find(q); } } public class Main { static List<List<Integer>> graph; static UF uf; public static void main(String[] args) { Scanner sc = new Scanner(System.in); graph = new ArrayList<>(); int n = sc.nextInt(); // 顶点数量 int A = sc.nextInt(); int m = sc.nextInt(); // 边的数量 for (int i = 1; i <= n; i++) { graph.add(new ArrayList<>()); // 为每个顶点初始化邻接列表 } for (int i = 0; i < m; i++) { String[] strs = sc.next().split(","); int u = Integer.parseInt(strs[0]); int v = Integer.parseInt(strs[1]); graph.get(u).add(v); graph.get(v).add(u); } //计算原来就认识的 int count = 0; //A的直接邻居 List<Integer> temp = graph.get(A); count += temp.size(); int res = 0; //并查集找到所有认识的 uf = new UF(n); dfs(A,n); for (int i = 0; i < n; i++) { if (i == A) continue; //二者相连就是认识 if (uf.isconnect(A, i)) { res++; } } System.out.println(res-count); } //递归找父节点与A相连通的 private static void dfs(int A,int n) { //A的直接邻居或者间接邻居 for (int node : graph.get(A)) { if (uf.isconnect(A, node)) continue; //把node作为A的父节点 uf.union(node, A); //顺着链找到最父节点进行递归 int root = uf.find(A); dfs(root,n); } } }