bzoj1602 [Usaco2008 Oct]牧场行走

24 篇文章 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


很简单的lca。但我闲着无聊打了个bfs……反正时限多

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
struct aaa{
    int to,next,v;
}e[5000000];
int n,m,cnt,x,y,z;
int head[100000];
int map[1001][1001];
bool mark[100000];
void ins(int u,int v,int w)
{
    e[++cnt].to=v;
    e[cnt].v=w;
    e[cnt].next=head[u];
    head[u]=cnt;
}
void insert(int u,int v,int w)
{
    ins(u,v,w);
    ins(v,u,w);
}
int bfs(int from)
{
    int queue[10000];
    int dist[10000];
    int t=0,w=1;
    bool mark[10000];
    memset(queue,0,sizeof(queue));
    memset(mark,0,sizeof(mark));
    memset(dist,0,sizeof(dist));
    queue[1]=from;
    mark[from]=1;
    while (t<w)
    {
        t++;
        int i=head[queue[t]];
        while (i)
        {
            if (!mark[e[i].to])
            {
                queue[++w]=e[i].to;
                dist[e[i].to]=dist[queue[t]]+e[i].v;
                mark[e[i].to]=1;
                if (e[i].to==y) return dist[y];
            }
            i=e[i].next;
        }
    }
    return dist[y];
}
int main()
{
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n-1;i++)
      {
        cin>>x>>y>>z;
        insert(x,y,z);
      }
    for (int i=1;i<=m;i++)
     {
        cin>>x>>y;
        memset(mark,0,sizeof(mark));
        cout<<bfs(x)<<endl;
     }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值