1076 Forwards on Weibo (30分)

    技术2022-07-10  116

    刚开始用自以为正确的递归BFS跑(实则为DFS),拿了大半的分数,很郁闷为什么不对,后来仔细一想我那个其实是DFS,在走一条路径的时候把后面的都处理掉了,导致丢失了数据。 修改后AC代码如下:

    #include<iostream> #include<vector> #include<map> #include<string.h> #include<queue> using namespace std; int N, L, val, num, fnum; map<int, int>Ma;//保存层数 vector < vector<int>>V(1001); bool flag[1010]; void BFS(int x) { queue<int>Q; Q.push(x); while (Q.size() > 0) { int t = Q.front(); Q.pop(); if (Ma[t] > L)break; flag[t] = true; fnum++; for (int i = 0; i < V[t].size(); i++) { if (flag[V[t][i]] == false) { Q.push(V[t][i]); flag[V[t][i]] = true; Ma[V[t][i]] = Ma[t] + 1; } } } } int main() { scanf("%d%d", &N, &L); for (int i = 1; i <=N; i++) { scanf("%d", &num); for (int j = 0; j < num; j++) { scanf("%d", &val); V[val].push_back(i); } } scanf("%d", &num); for (int i = 0; i < num; i++) { scanf("%d", &val); fnum = 0; memset(flag, false, sizeof(flag)); Ma.clear(); BFS(val); printf("%d\n", fnum-1); } return 0; }
    Processed: 0.033, SQL: 9