One day, Lin Ji wake up in the morning and found that his pethamster escaped. He searched in the room but didn’t find the hamster. He tried to use some cheese to trap the hamster. He put the cheese trap in his room and waited for
three days. Nothing but cockroaches was caught. He got the map of the school and foundthat there is no cyclic path and every location in the school can be reached from his room. The trap’s manual mention that the pet will always come back if it still in somewhere
nearer than distance D. Your task is to help Lin Ji to find out how many possible locations the hamster may found given the map of the school. Assume that the hamster is still hiding in somewhere in the school and distance between each adjacent locations is
always one distance unit.
1 10 2 0 1 0 2 0 3 1 4 1 5 2 6 3 7 4 8 6 9
2
很好的 bfs
# include<iostream>
# include<cstdio>
# include<vector>
# include<queue>
# include<algorithm>
# define N 100010
using namespace std;
vector<int >e[N];
int dis[N];
bool vis[N];
int main()
{
int T;
int i,n,d,a,b;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&d);
for(i=0; i<=n; i++)
{
e[i].clear();
dis[i] = N;
vis[i] = 0;
}
dis[0] = 0;
for(i=1; i<n; i++)
{
scanf("%d%d",&a,&b);
e[a].push_back(b);
e[b].push_back(a);
}
queue<int >q;
q.push(0);
vis[0] = 1;
while(!q.empty())
{
int x = q.front();
q.pop();
for(i=0; i<e[x].size(); i++)
{
int y = e[x][i];
if(!vis[y])
{
vis[y] = 1;
dis[y] = dis[x] + 1;
q.push(y);
}
}
}
int ans = 0;
for(i=0; i<n; i++)
if(dis[i] > d)
ans ++;
printf("%d\n",ans);
}
return 0;
}
模仿 , 学习 , 。。。
1372

被折叠的 条评论
为什么被折叠?



