这道题是计算weibo最大转发次数,使用BFS方法。
#include <iostream>
#include <string>
#include <set>
#include <map>
#include<queue>
#include<stack>
#include<algorithm>
//new and delete
//A1076 Forwards on Weibo
//这里结点从0编号到N-1
using namespace std;
const int MaxN = 2010;
struct Node {
int v; //编号
int layer=0; //层号
};
//被关注图,邻接表
vector<Node> G[MaxN];
bool visit[MaxN] = { false };
//N (≤1000), the number of users;
//and L (≤6), the number of levels of indirect followers that are counted
int N, L;
void PrintG() {
cout << "结点";
for (int i = 0; i < N; i++)
{
cout << endl;
for (int j = 0; j < G[i].size(); j++)
cout << G[i][j].v<<" ";
}
cout << endl;
}
//将所有结点层数变成0
void iniLayer() {
for (int i = 0; i < N; i++)
{
for (int j = 0; j < G[i].size(); j++)
G[i][j].layer = 0;
}
}
//BFS,返回转发数
int BFS(int x) {
queue< Node > q;
Node n;
n.v = x; n.layer = 0;
q.push(n);
visit[x] = true;
int num = -1; //转发数,-1是去掉自己转发
while (!q.empty()) {
//访问
n = q.front();
q.pop();
num++;
//后继结点入队
for (int i = 0; i < G[n.v].size(); i++) {
G[n.v][i].layer = n.layer + 1;
int N_v = G[n.v][i].v, N_l = G[n.v][i].layer;
if (visit[N_v] == false && N_l <= L) {
visit[N_v] = true;
q.push(G[n.v][i]);
}
}
}
return num;
}
int main() {
//Input data
cin >> N >> L;
for (int i = 0; i < N; i++) {
//输入是i关注的一群人
int j;
cin >> j;
for (int k = 0; k < j; k++) {
Node temp;
int a;
cin >> a;
a--;
temp.v = i;
G[a].push_back(temp);
}
}
vector<int> query_ind;
int i;
cin >> i;
for (int j = 0; j < i; j++) {
int temp;
cin >> temp;
query_ind.push_back(--temp);
}
//
//PrintG();
//
//output
for (int i = 0; i < query_ind.size(); i++) {
cout << BFS(query_ind[i]) << endl;
iniLayer();
fill(visit, visit + N,false);
}
return 0;
}