CF 342 E BFS搜索
题目链接
http://codeforces.com/problemset/problem/342/E
题意:有一颗n=100000个顶点,n-1条边的树,对其进行染色,开始时把1染成红色,其他的都为绿色,然后100000次操作,每次进行两种操作,把某个点染成红色,或者查询距离某个点最近的红色点的距离。
解题思路:由于题目数据范围较大,所以尽量要避免重复计算,对于每一个染成红色的点只搜一次,然后查询时输出答案即可。
代码:
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=150000;
int head[maxn],tol,stk[maxn],top,vis[maxn],dist[maxn],que[maxn*10],n;
struct node
{
int next,to;
}edge[18*maxn];
void add(int u,int v)
{
edge[tol].to=v;
edge[tol].next=head[u];
head[u]=tol++;
}
void bfs(int st)
{
int front=0,rear=0;
que[rear++]=st;
dist[st]=0;
while(front!=rear)
{
int u=que[front++];
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].to;
if(dist[v]>dist[u]+1)
{
dist[v]=dist[u]+1;
que[rear++]=v;
}
}
}
}
int main()
{
int i,j,k,m;
while(~scanf("%d%d",&n,&m))
{
memset(head,-1,sizeof(head));tol=0;
for(i=0;i<n-1;i++)
{
scanf("%d%D",&j,&k);
add(j,k);
add(k,j);
}
for(i=1;i<=n;i++)dist[i]=n+100;
bfs(1);
int top=0;
for (int i = 0; i < m; ++i)
{
int op, t2;
scanf("%d%d", &op, &t2);
if (op == 1)stk[top++]=t2;
else
{
if(top)
{
random_shuffle(stk,stk+top);
for(int pp=0;pp<top;++pp)bfs(stk[pp]);
top=0;
}
printf("%d\n", dist[t2]);
}
}
}
return 0;
}
#include<stdio.h>
#include<string.h>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=150000;
int head[maxn],tol,stk[maxn],top,vis[maxn],dist[maxn],que[maxn*10],n;
struct node
{
int next,to;
}edge[18*maxn];
void add(int u,int v)
{
edge[tol].to=v;
edge[tol].next=head[u];
head[u]=tol++;
}
void bfs(int st)
{
int front=0,rear=0;
que[rear++]=st;
dist[st]=0;
while(front!=rear)
{
int u=que[front++];
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].to;
if(dist[v]>dist[u]+1)
{
dist[v]=dist[u]+1;
que[rear++]=v;
}
}
}
}
int main()
{
int i,j,k,m;
while(~scanf("%d%d",&n,&m))
{
memset(head,-1,sizeof(head));tol=0;
for(i=0;i<n-1;i++)
{
scanf("%d%D",&j,&k);
add(j,k);
add(k,j);
}
for(i=1;i<=n;i++)dist[i]=n+100;
bfs(1);
int top=0;
for (int i = 0; i < m; ++i)
{
int op, t2;
scanf("%d%d", &op, &t2);
if (op == 1)stk[top++]=t2;
else
{
if(top)
{
random_shuffle(stk,stk+top);
for(int pp=0;pp<top;++pp)bfs(stk[pp]);
top=0;
}
printf("%d\n", dist[t2]);
}
}
}
return 0;
}

浙公网安备 33010602011771号