PAT甲级1076 Forwards on Weibo (30 分) :[C++题解]图论、bfs
生活随笔
收集整理的這篇文章主要介紹了
PAT甲级1076 Forwards on Weibo (30 分) :[C++题解]图论、bfs
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 題目分析
- 題目來源
題目分析
來源:acwing
分析:
BFS如何搜前k層?統計前k層的點數。
ac代碼
#include<bits/stdc++.h> using namespace std; const int N = 1010, M = 100010; int n,m;int h[N],e[M],ne[M],idx; bool st[N];//鄰接表加邊 void add(int a, int b){e[idx] = b, ne[idx] = h[a],h[a]= idx ++; }//bfs前m層的點數,除去根結點自身 int bfs(int start){queue<int> q;memset(st, 0 ,sizeof st);q.push(start);st[start] = true;int res = 0;for(int step = 0;step < m; step ++){int sz =q.size(); //一層有多少點res += sz;//擴展一層for(int i = 0; i<sz; i++){int t = q.front();q.pop();for(int j = h[t]; j != -1; j = ne[j]){int k = e[j];if(!st[k]){st[k] = true;q.push(k);}}}}return res + q.size() -1; }int main(){memset(h, -1, sizeof h);cin>> n >> m;for(int i =1; i<= n; i++ ){int cnt;cin >> cnt;while(cnt --){int x;cin >> x;add ( x,i);}}int k;cin >> k;while(k--){int x;cin >> x;printf("%d\n",bfs(x));} }題目來源
PAT甲級1076 Forwards on Weibo (30 分)
https://www.acwing.com/problem/content/1564/
總結
以上是生活随笔為你收集整理的PAT甲级1076 Forwards on Weibo (30 分) :[C++题解]图论、bfs的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PAT甲级1072 Gas Statio
- 下一篇: PAT甲级1112 Stucked Ke