問題是:代碼里面遞回DFS函式得引數不知道為什么++depth就是不能AC(只能得6分),depth+1才行
不知道是什么地方得問題
//DFS(a[n].at(i),++depth);、
//DFS(a[n].at(i),depth+1);
//此處得不能用DFS(a[n].at(i),++depth);,不知道為啥
這是題目
1004 Counting Leaves (30分)
A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.
Input Specification:
Each input file contains one test case. Each case starts with a line containing 0<N<100, the number of nodes in a tree, and M (<N), the number of non-leaf nodes. Then M lines follow, each in the format:
ID K ID[1] ID[2] ... ID[K]
where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID's of its children. For the sake of simplicity, let us fix the root ID to be 01.
The input ends with N being 0. That case must NOT be processed.
Output Specification:
For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.
The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output 0 1 in a line.
Sample Input:
2 1
01 1 02
Sample Output:
0 1
我的代碼:
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#define Max 105
vector<int> a[Max]; //vector得使用 ,定義一個二維不定長陣列
int N,M;
int MaxDep=-1;
int leaf[Max]={0};
void DFS(int n,int depth)
{
if(a[n].size()==0)
{
leaf[depth]++;
MaxDep=max(MaxDep,depth);
return ;
}
else
{
for(int i=0;i<a[n].size();i++) //a[n].size()獲取長度 a[n].at(i)訪問
{
//DFS(a[n].at(i),++depth);
DFS(a[n].at(i),depth+1); //此處得不能用DFS(a[n].at(i),++depth);,不知道為啥
}
}
return ;
}
int main()
{
#ifdef LOCAL
freopen("C:\\Users\\老子無敵天下第一\\Desktop\\1002.txt","r",stdin);
#endif
scanf("%d%d",&N,&M);
int r,k,c;
for(int i=1;i<=M;i++)
{ scanf("%d %d",&r,&k);
for(int j=1;j<=k;j++)
{
scanf("%d",&c);
a[r].push_back(c); //放入a[r] rear
}
}
DFS(1,1);
printf("%d",leaf[1]);
for(int i=2;i<=MaxDep;i++)
printf(" %d",leaf[i]);
return 0;
}
uj5u.com熱心網友回復:
for(int i=0;i<a[n].size();i++) //a[n].size()獲取長度 a[n].at(i)訪問{
//DFS(a[n].at(i),++depth);
(1)
DFS(a[n].at(i),depth+1); //此處得不能用DFS(a[n].at(i),++depth);,不知道為啥 (2)
(3)
}
從你的描述看,應該是:
如果是(2) ++depth 那么遞回呼叫結束后就是在(3) ,depth 將是 depth+1;
而(2)傳入 depth+1 ,遞回結束后,(3) 處依然是(1)處的depth
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/25891.html
標籤:C++ 語言
下一篇:關于快排的第一趟結果
