首页 > 试题广场 >

上述程序的输入为:

[单选题]
#include<bits/stdc++.h>
using namespace std;
vector<int>g[10];
int ans = 0;
void dfs(int x){
if(g[x].size() == 0){
ans++;
return;
}
for(int i = 0; i < g[x].size(); ++i){
dfs(g[x][i]);
}
}
int main(){
int n, x;
scanf("%d", &n);
for(int i = 2; i <= n; ++i){
scanf("%d", &x);
g[x].push_back(i);
}
dfs(1);
cout<<ans<<endl;
return 0;
}
上述程序的输入为:
9
1 2 2 1 5 6 6 6
则输出为( )
  • 4
  • 5
  • 6
  • 7

输入8个数,分别push到g[x]中,g[1][0]=2,g[2][0]=3,g[2][1]=4,g[1][1]=5,g[5][0]=6,g[6][0]=7,g[6][1]=8,g[6][2]=9

dfs(1)执行循环,执行dfs(2),dfs(5),然后2又变成3和4, 3的时候ans++,4的时候ans++,5变成6,6变成7,8,9,ans分别++三次,最后答案是5.

发表于 2019-09-24 21:00:50 回复(2)
哪位大哥来解析一下,我蒙
发表于 2019-09-13 08:20:02 回复(0)