【版本一:层次遍历思想,22分】
思想:开一个vector数组,记录每个节点的子节点;然后做一次层次遍历就好了。问题是如何区分两个不同的层次呢?这里我引入了一个last变量来记录每一个层次最后一个节点的值。这样只需要不停地更新last就好啦~
测试点一死活过不去,提示段错误!我要被折磨死了
#include <bits/stdc++.h>
using namespace std;
vector<int> v[110];
int main(void)
{
int N,M,last;
queue<int> q;
scanf("%d%d",&N,&M);
for(int i=0;i<M;i++)
{
int n,m,temp;
scanf("%d%d",&n,&m);
for(int j=0;j<m;j++)
{
scanf("%d",&temp);
v[n].push_back(temp);
}
}
q.push(1);
last=1;
while(!q.empty())
{
int temp,cnt=0;
while(q.front()!=last)
{
temp=q.front();
q.pop();
if(v[temp].size()==0) cnt++;
else
{
for(int i=0;i<v[temp].size();i++)
q.push(v[temp][i]);
}
}
temp=q.front();
q.pop();
if(v[temp].size()==0) cnt++;
else
{
for(int i=0;i<v[temp].size();i++)
q.push(v[temp][i]);
last=v[temp][v[temp].size()-1];
}
printf("%d",cnt);
if(!q.empty()) printf(" ");
}
}
【版本二:30分,AC】
原来是在更新last变量的时候出了问题,如果默认最后一个访问的结点有孩子,last才可以按版本一进行更新。否则会坏掉。所以直接在每层遍历的最后直接更新last为最后入队的元素就可以啦~
#include <bits/stdc++.h>
using namespace std;
vector<int> v[110];
int main(void)
{
int N,M,last;
queue<int> q;
scanf("%d%d",&N,&M);
for(int i=0;i<M;i++)
{
int n,m,temp;
scanf("%d%d",&n,&m);
for(int j=0;j<m;j++)
{
scanf("%d",&temp);
v[n].push_back(temp);
}
}
q.push(1);
last=1;
while(!q.empty())
{
int temp,cnt=0;
while(q.front()!=last)
{
temp=q.front();
q.pop();
if(v[temp].size()==0) cnt++;
else
{
for(int i=0;i<v[temp].size();i++)
q.push(v[temp][i]);
}
}
temp=q.front();
q.pop();
if(v[temp].size()==0) cnt++;
else
{
for(int i=0;i<v[temp].size();i++)
q.push(v[temp][i]);
}
last=q.back();
printf("%d",cnt);
if(!q.empty()) printf(" ");
}
}