1. 程式人生 > >圖的深搜和廣搜模板(多校聯合第一場Park Visit)

圖的深搜和廣搜模板(多校聯合第一場Park Visit)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;

int ans,end;
vector<int> graph[100001];
int visited[100001] = {0};

typedef struct{
	int v,n;
}Node; 

void dfs(int v)
{
    vector<int>::iterator it;
    visited[v] = 1;
    //printf("%5d", v);
    for (it = graph[v].begin(); it != graph[v].end(); ++it)
        if (!visited[*it])
            dfs(*it);
}
void bfs(int v)
{
    vector<int>::iterator it;
    queue<Node> q;
    Node node,node1;
    
    memset(visited,0,sizeof(visited));
    visited[v] = 1;
    node.v=v;node.n=0;
    q.push(node);
    
	while (!q.empty())
    {
        node = q.front();
        q.pop();
        for (it = graph[node.v].begin(); it != graph[node.v].end(); ++it)
            if (!visited[*it])
            {
                node1.v=(*it);node1.n=node.n+1;
                if(node1.n>ans) {
					ans=node1.n;end=node1.v;
				}
				visited[node1.v] = 1;
                q.push(node1);
            }
    }
}
int main()
{
	//freopen("input.txt","r",stdin);
    int T,i,m,n,a,b,K;
    scanf("%d",&T);
    while(T--)
    {
    	scanf("%d%d",&n,&m);
    	for(i=0;i<=n;i++)  
	        graph[i].clear();  //一定要注意使用vector每次要清空!!! 
    	for(i=1;i<n;i++)
    	{
    		scanf("%d%d",&a,&b);
    		graph[a].push_back(b);
    		graph[b].push_back(a);
    	}
    	
    	ans=0;end=0;
    	bfs(1);
    	ans=0;
    	bfs(end);
    	
		for(i=0;i<m;i++)
        {
        	scanf("%d",&K);
        	if(K-1<=ans) 
        	    printf("%d\n",K-1);
        	else
				printf("%d\n",ans+(K-ans-1)*2);
        }
    }
    return 0;
}


輸入樣例:

1
4 2
3 2
1 2
4 2
2
4