美文网首页
PAT甲级A1076---图的遍历

PAT甲级A1076---图的遍历

作者: 1nvad3r | 来源:发表于2020-09-04 16:44 被阅读0次

    1076 Forwards on Weibo (30分)

    1076
    分析:
    C++:
    #include <cstdio>
    #include <vector>
    #include <queue>
    #include <cstring>
    
    using namespace std;
    
    const int maxn = 1010;
    struct Node {
        int id;
        int layer;
    };
    vector<Node> G[maxn];
    bool inq[maxn];
    int n, l;
    
    int bfs(int index) {
        int forwardNum = 0;
        queue<Node> q;
        Node start;
        start.id = index;
        start.layer = 0;
        q.push(start);
        inq[start.id] = true;
        while (!q.empty()) {
            Node frontNode = q.front();
            q.pop();
            int front = frontNode.id;
            for (int i = 0; i < G[front].size(); i++) {
                Node nextNode = G[front][i];
                nextNode.layer = frontNode.layer + 1;
                if (inq[nextNode.id] == false && nextNode.layer <= l) {
                    q.push(nextNode);
                    inq[nextNode.id] = true;
                    forwardNum++;
                }
            }
        }
        return forwardNum;
    }
    
    int main() {
        Node user;
        scanf("%d%d", &n, &l);
        int followNum, followId;
        for (int i = 1; i <= n; i++) {
            user.id = i;
            scanf("%d", &followNum);
            for (int j = 0; j < followNum; j++) {
                scanf("%d", &followId);
                G[followId].push_back(user);
            }
        }
        int queryNum, s;
        scanf("%d", &queryNum);
        for (int i = 0; i < queryNum; i++) {
            memset(inq, false, sizeof(inq));
            scanf("%d", &s);
            int forwardNum = bfs(s);
            printf("%d\n", forwardNum);
        }
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:PAT甲级A1076---图的遍历

          本文链接:https://www.haomeiwen.com/subject/gfazsktx.html