题目来源
Forwards on Weibo (30)
注意点
- 下标从 1 开始
题目描述
Weibo is known as the Chinese version of Twitter. One user on Weibo may have many followers, and may follow many other users as well. Hence a social network is formed with followers relations. When a user makes a post on Weibo, all his/her followers can view and forward his/her post, which can then be forwarded again by their followers. Now given a social network, you are supposed to calculate the maximum potential amount of forwards for any specific user, assuming that only L levels of indirect followers are counted.
输入描述:
Each input file contains one test case. For each case, the first line contains 2 positive integers: N (<=1000), the number of users; and L (<=6), the number of levels of indirect followers that are counted. Hence it is assumed that all the users are numbered from 1 to N. Then N lines follow, each in the format:
M[i] user_list[i]
where M[i] (<=100) is the total number of people that user[i] follows; and user_list[i] is a list of the M[i] users that are followed by user[i]. It is guaranteed that no one can follow oneself. All the numbers are separated by a space.
Then finally a positive K is given, followed by K UserID’s for query.
输出描述:
For each UserID, you are supposed to print in one line the maximum potential amount of forwards this user can triger, assuming that everyone who can view the initial post will forward it once, and that only L levels of indirect followers are counted.
输入例子:
7 3 3 2 3 4 0 2 5 6 2 3 1 2 3 4 1 4 1 5 2 2 6输出例子:
4 5思路简介
广搜+深度记录
链式前向星建图,然后记录深度广搜即可,在 PAT 当中出现很多次了
记录深度也很简单
- num 记录当前层有几个元素
- high 记录深度
- 每次取出
num--当num=0时说明遍历完一层high++,此时队列的长度即下一层的大小,num=q.size()
这里注意一下,一个人转发了之后,他的所有关注者都会看见,只有其中没转发过的人才会转发,
遇到的问题
- 小标从 1 开始,vector存在下标越界的问题,要多开一个空间或者下标减 1
- Edge数组一开始开小了,应该开N*N
代码
/** * https://www.nowcoder.com/pat/5/problem/4306 * 广搜 */#include<bits/stdc++.h>usingnamespacestd;constintN=1000+7;structEdge{intto,next;Edge():to(-1),next(-1){}Edge(intto,intnext):to(to),next(next){}}e[N*N];inthead[N],cnt=0;voidadd(intu,intv){e[cnt]={v,head[u]};head[u]=cnt++;}intn,l;voidinput(){memset(head,-1,sizeof(head));cin>>n>>l;for(inti=0;i<n;++i){intm;cin>>m;for(intj=0;j<m;++j){intv;cin>>v;add(v,i+1);}}}voidsolve(){intk;cin>>k;queue<int>q;vector<int>vis(n+1);q.push(k);intres=0,high=0,num=1;vis[k]=1;while(!q.empty()&&high<l){intu=q.front();q.pop();num--;for(inti=head[u];i!=-1;i=e[i].next){if(!vis[e[i].to]){res++;vis[e[i].to]=1;q.push(e[i].to);}}if(!num){high++;num=q.size();}}cout<<res<<'\n';}intmain(){ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);//fstream in("in.txt",ios::in);cin.rdbuf(in.rdbuf());input();intT=1;cin>>T;while(T--){solve();}return0;}