School Regional Team Contest, Saratov, 2011-F. Spiders-求树直径

http://codeforces.com/problemset/problem/120/F

给n棵树,

求每棵树直径之和。。

用两个bfs的方法。。23333做n次

#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <iostream>
using namespace std;

const int N = 1000000000; 
struct node
{
    int v,w;
    int step;
    node(int a=0,int b=0,int c=0)
    {
        v=a;
        w=b;
        step=c;
    }
};
vector <node >sb[105];
queue<node> q;
int vis[105];
int main(  )
{
	freopen( "input.txt","r",stdin ); // scanf 从1.txt输入
	 freopen( "output.txt","w",stdout );  //printf输出到1.tx
    int i,j,k;
	int x,y;
	int n;
	cin>>n;
	int sum=0;
	for (k=1;k<=n;k++)
	{
		memset(vis,0,sizeof(vis));
		while(!q.empty()) q.pop();
		
		int m;
		cin>>m;
		for (j=1;j<=m;j++)
			sb[j].clear();

		for (j=1;j<=m-1;j++)
		{
			scanf("%d%d",&x,&y);
			sb[x].push_back(node(y,1));
			sb[y].push_back(node(x,1)); 
		} 
		int fardist=0;
		int fardisti=0;
		q.push(node(1,0,0));
		vis[1]=1;
		while(!q.empty())
		{
			node tp=q.front();
			q.pop();
			for (i=0;i<sb[tp.v].size();i++)
			{
				int w=sb[tp.v][i].w;
				int v=sb[tp.v][i].v;
				if (vis[v]) continue;
				vis[v]=1;
				q.push(node(v,w,tp.step+w));
				if (tp.step+w>fardist)
				{
					fardisti=v;
					fardist=tp.step+w;
				}
			}
		}
		//    printf("%d-%d\n",fardisti,fardist);
		memset(vis,0,sizeof(vis));
		while(!q.empty()) q.pop();
		q.push(node(fardisti,0,0));
		vis[fardisti]=1;
		while(!q.empty())
		{
			node tp=q.front();
			q.pop();
			for (i=0;i<sb[tp.v].size();i++)
			{
				int w=sb[tp.v][i].w;
				int v=sb[tp.v][i].v;
				if (vis[v]) continue;
				vis[v]=1;
				q.push(node(v,tp.w,tp.step+w));
				if (tp.step+w>fardist)
				{
					fardisti=v;
					fardist=tp.step+w;
				}
			}
		} 
	sum+=fardist;
	}
    printf("%d\n",sum);
    return 0;
}


你可能感兴趣的:(School Regional Team Contest, Saratov, 2011-F. Spiders-求树直径)