cin默认是用十进制解析的,所以不需要特殊处理字符串
BFS(宽度优先遍历)
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
const int N = 110, M = N * N;
int e[M], ne[M], idx, h[N];
int son[N];
vector<int> Res;
// 让字符变成int类型变量
int Disp (string a)
{
int res = 0;
for (int i = a.size() - 1, p = 1; i >= 0; i -- )
{
res = res + (a[i] - '0') * p;
p *= 10;
}
return res;
}
// 建立链表
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
void bfs()
{
queue<int> q;
q.push(0);
while (q.size())
{
int t = q.size(), cnt = 0;
for (int i = 0; i < t ;i ++ )
{
auto a = q.front();
q.pop();
for (int j = h[a]; ~j; j = ne[j])
{
int k = e[j];
if (son[k] == 0)
cnt ++ ;
q.push(k);
}
}
Res.push_back(cnt);
}
}
int main()
{
int n, m;
scanf("%d %d", &n, &m);
memset(h, -1, sizeof h);
// 处理输入
while (m -- )
{
string non_leaf;
int child;
cin >> non_leaf >> child;
int disp = Disp(non_leaf);
son[disp] = child;
while (child -- )
{
string leaf;
cin >> leaf;
int di = Disp(leaf);
add(disp, di);
}
}
add(0, 1);
bfs();
Res.pop_back();
for (int i = 0; i < Res.size() - 1; i ++ ) cout << Res[i] << ' ';
cout << Res.back() << endl;
return 0;
}
DFS
#include <bits/stdc++.h>
using namespace std;
const int N = 110, M = N * N;
int e[N], ne[N], h[N], idx;
bool Whether[N];
int res[N];
bool st[N];
int son[N];
vector<int> Res;
//建立链表
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
//深度优先遍历
void dfs(int u, int distance)
{
st[u] = true;
Whether[distance] = true;
if (!son[u])
{
res[distance] ++ ;
return ;
}
for (int i = h[u]; i != -1; i = ne[i])
{
int j = e[i];
if (!st[j])
{
dfs(j, distance + 1);
}
}
}
int main()
{
int n, m;
cin >> n >> m;
memset(h, -1, sizeof h);
// 处理输入
while (m --)
{
int father, several;
cin >> father >> several;
son[father] = several;
while (several -- )
{
int children;
cin >> children;
add(father, children);
}
}
dfs(1, 0);
Whether[0] = true;
//处理输出
for (int i = 0; i < N; i ++ )
{
if (Whether[i]) Res.push_back(res[i]);
else break;
}
for (int i = 0; i < Res.size() - 1; i ++ )
cout << Res[i] << ' ';
cout << Res.back() << endl;
return 0;
}