boj 196

Description
CC lives on the  tree which has N nodes.On every leaf of the tree there is an apple(leaf means there is only one branch connect this node ) .Now CC wants to get two apple ,CC can choose any node to start and the speed of CC is one meter per second.
now she wants to know the shortest time to get two apples;
 
input
Thers are many cases;
The  first line of every case  there is a number N(2<=N<=10000)
if n is 0 means the end of input.
Next there is n-1 lines,on the  i+1 line there is three number ai,bi,ci
which means there is a branch connect node ai and node bi.
(1<=ai, bi<=N , 1<=ci<=2000)
ci means  the len of the branch  is ci meters ;
 
output 
print the mininum time to get only two apple;
 
sample input
7
1 2 1
2 3 2
3 4 1
4 5 1
3 6 3
6 7 4
0
 
sample output
5

 

以前做的题,开始时没有建树,不知道为什么一直RE,后来参考别人代码用STL vector建了树,过了

#include<iostream>
#include<vector>
using namespace std;
#define maxn 10005
#define maxlen 30000000
int que[maxn];
int cntnum[maxn];
int dp[maxn][2];
bool flag[maxn];
int xx = 0;
struct info{
	int v;
	int e;
};
vector<info>graph[maxn];
int minlen,n;
void dfs(int root)
{
	que[xx++]=root;
	flag[root]=true;
	int len=graph[root].size();
	for(int i=0;i<len;i++)
	{
		if(!flag[graph[root][i].v])
			dfs(graph[root][i].v);
	}
}
int main()
{
	scanf("%d",&n);
	while(n)
	{
		int minlen = maxlen;
		for(int i=1;i<=n;i++)
		{
			flag[i]=false;
			graph[i].clear();
			cntnum[i]=0;
			dp[i][0]=maxlen;
			dp[i][1]=maxlen+1;
		}
		for(int i=0;i<n-1;i++)
		{
			int ai,bi,ci;
			info temp;
			scanf("%d %d %d",&ai,&bi,&ci);
			temp.v=bi;
			temp.e=ci;
			graph[ai].push_back(temp);
			temp.v=ai;
			temp.e=ci;
			graph[bi].push_back(temp);
			cntnum[ai]++;
			cntnum[bi]++;
		}
		if(n==2)
		{
			printf("%d\n",graph[1][0].e);
			scanf("%d",&n);
			continue;
		}
		int root;
		for(int i=1;i<=n;i++)
		{
			if(cntnum[i]>1)
			{
				root=i;
				break;
			}
		}
		xx=0;
		dfs(root);
		for(int i=n-1;i>=0;i--)
		{
			if(graph[que[i]].size()==1)
				dp[que[i]][0]=dp[que[i]][1]=0;
			else
			{
				int len=graph[que[i]].size();
				for(int j=0;j<len;j++)
				{
					if(dp[que[i]][0]>dp[graph[que[i]][j].v][0]+graph[que[i]][j].e)
					{
						dp[que[i]][1]=dp[que[i]][0];
						dp[que[i]][0]=dp[graph[que[i]][j].v][0]+graph[que[i]][j].e;
					}
					else
					{
						if(dp[que[i]][1]>dp[graph[que[i]][j].v][0]+graph[que[i]][j].e)
							dp[que[i]][1]=dp[graph[que[i]][j].v][0]+graph[que[i]][j].e;
					}
				}
				if(minlen>dp[que[i]][0]+dp[que[i]][1])
					minlen=dp[que[i]][0]+dp[que[i]][1];
			}
		}
		printf("%d\n",minlen);
		scanf("%d",&n);
}
	//system("pause");
	return 0;
}

 

你可能感兴趣的:(BO)