1013 25 Battle Over Cities DFS or 并查集 求解连通分量个数 1021 25 Deepest Root DFS 连通分量 统计最深 做不出来 1034 30 Head of a Gang DFS or 并查集 1076 30 Forwards on Weibo DFS or BFS 统计数量 1003 25 Emergency 1018 30 Public Bike Management Dijkstra+DFS 我去真难 1030 30 Travel Plan Dijkstra 结点花费最少 输出一条路径 有手就行 1072 30 Gas Station 1087 30 All Roads Lead to Rome Dijkstra +DFS 结点权重
🤔注意很多题目的索引是从1开始的
图的遍历
DFS
深度搜索的同时记录深度
1 2 3 4 5 6 7 8 9 10 11
voidDFS(int r,int depth){ if (depth <= D) { ans.insert(r); } if (depth > D) return; flag[r] = depth; for (int i = 0; i < G[r].size(); i++) { if ((!flag[G[r][i]])||flag[G[r][i]]>depth+1) DFS(G[r][i], depth + 1); } }
#include<iostream> usingnamespace std; constint maxn = 1010; int N, M, K, G[maxn][maxn]; bool flag[maxn]; voidDFS(int r){ flag[r] = true; for (int i = 1; i <= N; i++) { if (!flag[i] && G[r][i]) { DFS(i); } } } intmain(){ cin >> N >> M >> K; int a, b; for (int i = 1; i <= M; i++) { cin >> a >> b; G[a][b] = G[b][a] = 1; } for (int i = 0; i < K; i++) { int cnt = 0, city; cin >> city; fill(flag, flag + maxn, false); flag[city] = true; for (int i = 1; i <= N; i++) { if (!flag[i]) { cnt++; DFS(i); } } cout << cnt - 1 << endl; } }
#include<iostream> #include<vector> #include<set> usingnamespace std; constint maxn = 1010; int N, M, K, F[maxn]; vector<int>G[maxn]; intfindFather(int i){ int x = i; while (F[x] != x) x = F[x]; //此时x是根节点 while (F[i] != x) { int t = F[i]; F[i] = x; i = t; } return x; } intmain(){ cin >> N >> M >> K; int a, b; for (int i = 1; i <= M; i++) { cin >> a >> b; G[a].push_back(b); G[b].push_back(a); } int city; for (int i = 0; i < K; i++) { cin >> city; for (int j = 1; j <= N; j++) {//初始化 F[j] = j; } for (int j = 1; j <= N; j++) { if (j == city) continue; for (int k = 0; k < G[j].size(); k++) { if (G[j][k] == city) continue; int fa = findFather(j); int fb = findFather(G[j][k]); if (fa != fb) { F[fa] = fb; } } } set<int> roots; for (int j = 1; j <= N; j++) { if (j == city) continue; int r = findFather(j);//注意这里不是r = F[j] roots.insert(r); } cout << roots.size() - 1 << endl; } }
#include<iostream> #include<vector> #include<set> usingnamespace std; constint maxn = 10010; int N, G[maxn][maxn]; bool flag[maxn]; int big = 0; vector<int>far; voidDFS(int root, int d){ if (d > big) { big = d; far.clear(); far.push_back(root); } elseif (d == big) { far.push_back(root); } flag[root] = true; for (int i = 1; i <= N; i++) { if (!flag[i] && G[root][i]) DFS(i, d + 1); } } intmain(){ cin >> N; int a, b; for (int i = 1; i <= N - 1; i++) { cin >> a >> b; G[a][b] = G[b][a] = 1; } //统计联通分量 int cnt = 0; for (int i = 1; i <= N; i++) { if (!flag[i]) { cnt++; DFS(i, 1); } } if (cnt > 1) { cout << "Error: " << cnt << " components\n"; return0; } set<int>ans; for (int i = 0; i < far.size(); i++) { ans.insert(far[i]); } far.clear(); big = 0; auto p = ans.begin(); fill(flag, flag + maxn, false); DFS(*p, 1); for (int i = 0; i < far.size(); i++) { ans.insert(far[i]); } for (auto p = ans.begin(); p != ans.end(); p++) { cout << *p << endl; } }