- 本题就是dfs.连通图个数-2;
- 但是java慢,最后一个case 超时
import java.io.*; import java.util.HashSet; import java.util.Set; public class Main { @SuppressWarnings("uncheck") public static void main(String[] args) throws IOException { StreamTokenizer st = new StreamTokenizer(new InputStreamReader(System.in)); int n, m, k; st.nextToken(); n = (int) st.nval; st.nextToken(); m = (int) st.nval; st.nextToken(); k = (int) st.nval; Set<Integer>[] g = new HashSet[n + 1]; for (int i = 0; i <= n; i++) { g[i] = new HashSet<>(); } for (int i = 0; i < m; i++) { st.nextToken(); int city1 = (int) st.nval; st.nextToken(); int city2 = (int) st.nval; g[city1].add(city2); g[city2].add(city1); } PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); for (int i = 0; i < k; i++) { st.nextToken(); int city = (int) st.nval; Set<Integer> connected = new HashSet<>(g[city]); visited = new boolean[n + 1]; g[city] = new HashSet<>(); for (int connectedcity : connected) { g[connectedcity].remove(city); } int cnt = travel(g, n); out.println(cnt - 2); for (int connectedcity : connected) { g[connectedcity].add(city); } g[city] = connected; } out.flush(); } static boolean[] visited; public static int travel(Set<Integer>[] g, int n) { int count = 0; for (int i = 1; i <= n; i++) { if (!visited[i]) { travel(i, g); count++; } } return count; } public static void travel(int start, Set<Integer>[] g) { visited[start] = true; for (int city : g[start]) { if (!visited[city]) { travel(city, g); } } } }
标签:city,PAT,int,Over,st,nval,Battle,new,nextToken From: https://www.cnblogs.com/fishcanfly/p/17794744.html