1076. Forwards on Weibo (30)

GitHub加载慢得让人想哭。

虽然博客广告多,也只能先发在这里了,什么时候觉得太闲了,那时再去搞个个人网站。


用邻接表表存储图的边。

这道题,我第一次提交的时候最后一个测试用例的运行时间是1200+ms!

左思右想,左改右改,始终不知其然。后来参考了别的小伙伴的代码,把使用作为链表的forward_list改成vector,立马提速到100+ms。

至今还不知道为何使用链表的容器适配器会这么慢,对容器的性能分析还很生疏。路漫漫其修远兮,吾将上下而求索。


#include <iostream>
#include <vector>
#include <queue>
using namespace std;

class MyGraph {
public:
    MyGraph(const int &vertexCnt);
    ~MyGraph();
    //增加一条从indexA指向indexB的弧。
    void addEdge(const int &indexA, const int &indexB);
    //返回从指定index开始,指定level的搜索顶点数,不包活index这点。
    int BFS(const int &index, const int &level, const int &mark);

private:
    struct Vertex {
        //每次重置顶点,将会耗费大量时间,因此将判断是否访问过设置成判断数值的形式。
        //在BFS中,传入一个参数mark,作为判断标志。
        int visitNum;
        vector<int> edge;		//边数值表示“指向该点”的顶点索引。
        //vector比forward_list快很多!!!为什么呢?
    };
    int vertexCnt;
    Vertex *pVertex;	//索引表示顶点。用固定数组会更快一些,o(╯□╰)o。
};

inline
MyGraph::MyGraph(const int &vertexCnt): vertexCnt(vertexCnt) {
    pVertex = new Vertex[vertexCnt]();  //值初始化。
}

inline
MyGraph::~MyGraph() {
    delete[] pVertex;
}

inline
void MyGraph::addEdge(const int &indexA, const int &indexB) {
    pVertex[indexA].edge.push_back(indexB);
}

int MyGraph::BFS(const int &index, const int &level, const int &mark) {
    int layer(0);
    int ret(0);

    queue<int> que;
    que.push(index);
    pVertex[index].visitNum = mark + 1;
    auto oneLayerCnt = que.size();

    while (!que.empty()) {
        int tmp(que.front());
        que.pop();
        --oneLayerCnt;

        auto last = pVertex[tmp].edge.end();
        for (auto iter = pVertex[tmp].edge.begin(); iter != last; ++iter) {
            if (pVertex[*iter].visitNum != mark + 1) {
                que.push(*iter);
                pVertex[*iter].visitNum = mark + 1;
                ++ret;
            }
        }

        if (oneLayerCnt == 0) {
            ++layer;
            oneLayerCnt = que.size();
        }
        if (layer == level) break;
    }

    return ret;
}


int main(void) {
    int num, level;
    scanf("%d%d", &num, &level);
    MyGraph graph(num);
    for (int i(0); i < num; ++i) {
        int numsOfFlollow, follow;
        scanf("%d", &numsOfFlollow);
        for (int k(0); k < numsOfFlollow; ++k) {
            scanf("%d", &follow);
            //i 关注了 follow-1,所以有一条从follow-1 到 i 的弧。
            graph.addEdge(follow - 1, i);
        }
    }

    int k, x;
    scanf("%d", &k);
    for (int i(0); i < k; ++i) {
        scanf("%d", &x);
        cout << graph.BFS(x - 1, level, i) << endl;
    }

    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值