zoukankan      html  css  js  c++  java
  • bzoj1602 [Usaco2008 Oct]牧场行走

    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;
         }
    }
    

      

    ——by zhber,转载请注明来源
  • 相关阅读:
    增量式爬虫 Scrapy-Rredis 详解及案例
    scrapy-redis使用以及剖析
    为什么代码要写到匿名自执行函数中?
    Vue组件第三天--webpack
    Vue组价通信
    Vue组件第一天
    pip3 install pycryptohome
    selenium 安装与 chromedriver安装
    解决:'chromedriver' executable needs to be in PATH问题
    如何在VS Code中编写Python
  • 原文地址:https://www.cnblogs.com/zhber/p/4035978.html
Copyright © 2011-2022 走看看