当前位置: 代码迷 >> 综合 >> BFS-BZOJ-1602-[Usaco2008 Oct]牧场行走
  详细解决方案

BFS-BZOJ-1602-[Usaco2008 Oct]牧场行走

热度:40   发布时间:2023-12-20 21:21:40.0

Description

N头牛(2<=n<=1000)别人被标记为1到n,在同样被标记1到n的n块土地上吃草,第i头牛在第i块牧场吃草。 这n块土地被n-1条边连接。 奶牛可以在边上行走,第i条边连接第Ai,Bi块牧场,第i条边的长度是Li(1<=Li<=10000)。 这些边被安排成任意两头奶牛都可以通过这些边到达的情况,所以说这是一棵树。 这些奶牛是非常喜欢交际的,经常会去互相访问,他们想让你去帮助他们计算Q(1<=q<=1000)对奶牛之间的距离。
Input

*第一行:两个被空格隔开的整数:N和Q

*第二行到第n行:第i+1行有两个被空格隔开的整数:AI,BI,LI

*第n+1行到n+Q行:每一行有两个空格隔开的整数:P1,P2,表示两头奶牛的编号。
Output

*第1行到第Q行:每行输出一个数,表示那两头奶牛之间的距离。
Sample Input
4 2

2 1 2

4 3 2

1 4 3

1 2

3 2

Sample Output
2

7


题解:
其实就是一个对树的BFS,当然还有更简单的做法,我选了无脑的搜搜搜。


#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <queue>
#define MAXN 1005
#define INF 0x7fffffff
using namespace std;
int n,q;
bool vis[MAXN];
typedef struct edge
{int v,cost;edge(int _v=0,int _cost=0):v(_v),cost(_cost){}
}Edge;
vector<Edge>E[MAXN];
void addedge(int u,int v,int cost)
{E[u].push_back(edge(v,cost));E[v].push_back(edge(u,cost));
}
typedef struct qnode
{int num;long long int total;qnode(int _num=0,long long int _total=0):num(_num),total(_total){}
}Qnode;
queue<Qnode>Q;
long long int bfs(int u,int v)
{Qnode now,tmp;memset(vis,0,sizeof(vis));while(!Q.empty()) Q.pop();Q.push(qnode(u,0));while(!Q.empty()){now=Q.front();Q.pop();if(now.num==v)return now.total;for(int i=0;i<E[now.num].size();i++){if(vis[E[now.num][i].v]==0){tmp.num=E[now.num][i].v;tmp.total=now.total+E[now.num][i].cost;vis[E[now.num][i].v]=1;Q.push(tmp);}}}return 0;
}
int main()
{int a,b,l;cin >> n >> q;for(int i=1;i<n;i++){scanf("%d%d%d",&a,&b,&l);addedge(a,b,l);}for(int i=1;i<=q;i++){scanf("%d%d",&a,&b);cout << bfs(a,b) << endl;}return 0;
}