首页 > 代码库 > PAT 1076. Forwards on Weibo (30)

PAT 1076. Forwards on Weibo (30)

题目地址:http://pat.zju.edu.cn/contests/pat-a-practise/1076

此题考查图的遍历操作:

本来我个人觉得可以用dfs的,但是不知何故,有两个case没有过,贴出代码,望指出错误之处:

#include <cstdio>
#include <map>
#include <vector>
#include <memory.h>
using namespace std;

const int NUM=1001;
bool visited[NUM];
int forwards;
map<int,vector<int> > adjlist;

void reset()
{
    memset(visited,false,sizeof(bool)*NUM);
    forwards=0;
}

void dfs(int sourceNode,int indLevel,int L)
{
    if(indLevel>L)
        return;
    for(vector<int>::iterator iter=adjlist[sourceNode].begin();iter!=adjlist[sourceNode].end();++iter)
    {
        if(!visited[*iter])
        {
            ++forwards;
            visited[*iter]=true;
            dfs(*iter,indLevel+1,L);
        }
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    int N,L;
    scanf("%d %d",&N,&L);
    if(L>6)
        L=6;
    int i,Mi,j,followed;
    for(i=1;i<=N;++i)
    {
        scanf("%d",&Mi);
        for(j=0;j<Mi;++j)
        {
            scanf("%d",&followed);
            adjlist[followed].push_back(i);
        }
    }
    int K,query;
    scanf("%d",&K);
    for(i=0;i<K;++i)
    {
        scanf("%d",&query);
        reset();
        visited[query]=true;
        dfs(query,1,L);
        printf("%d\n",forwards);
    }
    return 0;
}
View Code

 

后来换了bfs后,AC了:

#include <cstdio>
#include <map>
#include <vector>
#include <queue>
#include <memory.h>
using namespace std;

const int NUM=1001;

bool  hasForward[NUM];
int forwards;
map<int,vector<int> > adjlist;
queue<int> recordQueue;

void reset()
{
    memset(hasForward,false,sizeof(bool)*NUM);
    forwards=0;
    while(!recordQueue.empty())
        recordQueue.pop();
}

void bfs(int query,int level)
{
    int curLevel=1;
    hasForward[query]=true;
    recordQueue.push(query);
    int endOfLevel=recordQueue.back();
    int cur;
    while(!recordQueue.empty()&&curLevel<=level)
    {
        cur=recordQueue.front();
        recordQueue.pop();
        for(vector<int>::iterator iter=adjlist[cur].begin();iter!=adjlist[cur].end();++iter)
        {
            if(!hasForward[*iter])
            {
                recordQueue.push(*iter);
                ++forwards;
                hasForward[*iter]=true;
            }
        }
        if(cur==endOfLevel)
        {
            ++curLevel;
            endOfLevel=recordQueue.back();
        }
    }
}
int _tmain(int argc, _TCHAR* argv[])
{
    int N,L;
    scanf("%d %d",&N,&L);
    if(L>6)
        L=6;
    int i,j;
    int Mi,followed;
    for(i=1;i<=N;++i)
    {
        scanf("%d",&Mi);
        for(j=0;j<Mi;++j)
        {
            scanf("%d",&followed);
            adjlist[followed].push_back(i);
        }
    }
    int K,query;
    scanf("%d",&K);
    for(i=0;i<K;++i)
    {
        scanf("%d",&query);
        reset();
        bfs(query,L);
        printf("%d\n",forwards);
    }
    return 0;
}
View Code