csu oj 1010 Water Drinking(BFS)
思路:从根节点BFS 看哪个树枝最短,如果有多个,则取多个的最小值即可。
#include <cstdio>
#include <cstring>
#include <map>
#include <queue>
#include <algorithm>
using namespace std;
#define M 100005
#define INF 1<<29
#define CLS(x,v) memset(x,v,sizeof(x))
int right[M];
int head[M];
void link(int x,int y){right[x]=y;}
int main()
{
int n,cnt;
int a,b;
while(~scanf("%d",&n))
{
CLS(right,-1);
cnt=0;
for(int i=0;i<n;i++)
{
scanf("%d%d",&a,&b);
if(a==0)head[cnt++]=b;
else link(a,b);
}
int ans=n,flag=1;
while(flag)
{
for(int i=0;i<cnt;i++)
{
//看哪个树枝最短,如果有多个,则取多个的最小
if(right[head[i]]==-1)
{
ans=min(ans,head[i]);
flag=0;
}
head[i]=right[head[i]];
}
}
printf("%d\n",ans);
}
return 0;
}
本文介绍了一个基于广度优先搜索(BFS)的算法实现,用于寻找从根节点出发到叶节点的最短路径。该算法适用于解决特定类型的图遍历问题,通过不断扩展距离根节点最近的节点来寻找最短路径。
342

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



