图的存储方式:




dfs:

bfs(层遍历):

https://www.starrycoding.com/problem/42
// Problem: ${json.name}
// Contest: ${json.group}
// URL: ${json.url}
// Memory Limit: ${json.memoryLimit} MB
// Time Limit: ${json.timeLimit} ms
// More thought is needed
#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
vector<int> fa[60];
void dfs(int n) {//深度遍历
cout << n << " ";
for (auto& i : fa[n]) {
dfs(i);
}
}
void bfs(int n) {//广度遍历
queue<int> qe;//尾进头出
qe.push(n);
while (qe.size()) {
int x = qe.front();//一边压入一边输出
qe.pop();
cout << x << " ";
for (auto& i : fa[x]) qe.push(i);
}
}
void solve() {
int n;
cin >> n;
for (int i = 2; i <= n; i++) {
int fa_i;
cin >> fa_i;
fa[fa_i].push_back(i);//邻接表存储法
}
dfs(1);
cout << endl;
bfs(1);
}
signed main() {
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
solve();
return 0;
}
https://www.starrycoding.com/problem/64

标记法,将从1经过的点全部标记
// Problem: ${json.name}
// Contest: ${json.group}
// URL: ${json.url}
// Memory Limit: ${json.memoryLimit} MB
// Time Limit: ${json.timeLimit} ms
// More thought is needed
#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
const int N = 1e5 + 9;
vector<int> v[N];
bitset<N> vis;//标记数组
void find_v(int n) {
vis[n] = true;
for (auto& i : v[n]) {//dfs
if (vis[i]) {//如果标记过了,则跳过,回环
continue;
}
find_v(i);
}
}
void solve() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int k, j;
cin >> k >> j;
if (k != j) v[k].push_back(j);//剔除自回环
}
find_v(1);
for (int i = 1; i <= n; i++) {
if (vis[i]) cout << i << " ";//全遍历,验证标记
}
}
signed main() {
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
solve();
return 0;
}
https://www.starrycoding.com/problem/30
递归回溯,用vis标记已使用过的元素,再全遍历即可得到答案
// Problem: ${json.name}
// Contest: ${json.group}
// URL: ${json.url}
// Memory Limit: ${json.memoryLimit} MB
// Time Limit: ${json.timeLimit} ms
// More thought is needed
#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
vector<int> res;
bitset<15> vis;//为什么是15呢
void arr(int n, int len) {
if (len == n) {
for (auto& i : res) {
cout << i << " ";
}
cout << endl;
return;
}
for (int i = 1; i <= n; i++) {
if (vis[i]) continue;//剪枝
vis[i] = true;//标记
res.push_back(i);
len++;
arr(n, len);
vis[i] = false;//回溯
res.pop_back();
len--;
}
}
void solve() {
int n;
cin >> n;
arr(n, 0);
}
signed main() {
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
solve();
return 0;
}
https://www.starrycoding.com/problem/67
有空再写