• BZOJ 1602: [Usaco2008 Oct]牧场行走( 最短路 )


    一棵树..或许用LCA比较好吧...但是我懒...写了个dijkstra也过了..

    ----------------------------------------------------------------------------

    #include<cstdio>
    #include<algorithm>
    #include<queue>
    #include<cstring>
    #include<iostream>
     
    #define rep( i , n ) for( int i = 0 ; i < n ; ++i )
    #define clr( x , c ) memset( x , c , sizeof( x ) )
     
    using namespace std;
     
    typedef pair< int , int > pii;
     
    const int maxn = 1000 + 5;
    const int inf = 0x3f3f3f3f;
     
    struct edge {
    int to , dist;
    edge* next;
    };
     
    edge* pt;
    edge* head[ maxn ];
    edge EDGE[ maxn << 1 ];
     
    void init() {
    pt = EDGE;
    clr( head , 0 );
     
    inline void add( int u , int v , int d ) {
    pt -> to = v;
    pt -> dist = d;
    pt -> next = head[ u ];
    head[ u ] = pt++;
    }
     
    #define add_edge( u , v , d ) add( u , v , d ) , add( v , u , d )
     
    int d[ maxn ][ maxn ];
     
    void dijkstra( int S ) {
    clr( d[ S ] , inf );
    d[ S ][ S ] = 0;
    priority_queue< pii , vector< pii > , greater< pii > > Q;
    Q.push( make_pair( 0 , S ) );
    while( ! Q.empty() ) {
    int x = Q.top().second , dist = Q.top().first;
    Q.pop();
    if( dist != d[ S ][ x ] ) continue;
    for( edge* e = head[ x ] ; e ; e = e -> next )
       if( d[ S ][ e -> to ] > dist + e -> dist ) {
       
        d[ S ][ e -> to ] = dist + e -> dist;
       
        Q.push( make_pair( d[ S ][ e -> to ] , e -> to ) );
       
       }
       
    }
    }
     
    int main() {
    init();
    int n , q;
    cin >> n >> q;
    rep( i , n - 1 ) {
    int u , v , d;
    scanf( "%d%d%d" , &u , &v , &d );
    add_edge( u - 1 , v - 1 , d );
    }
    rep( i , n ) dijkstra( i );
    while( q-- ) {
    int u , v;
    scanf( "%d%d" , &u , &v );
    printf( "%d " , d[ u - 1 ][ v - 1 ] );
    }
    return 0;
    }

    ----------------------------------------------------------------------------

    1602: [Usaco2008 Oct]牧场行走

    Time Limit: 5 Sec  Memory Limit: 64 MB
    Submit: 1351  Solved: 684
    [Submit][Status][Discuss]

    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

    HINT

    Source

  • 相关阅读:
    线性反馈系统
    静磁场
    平面波的传播
    Partition does not end on cylinder boundary
    FFTW简介及使用
    EINTR、ERESTARTSYS和SIGINT
    凉面
    linux Shell编程
    Linux From Scratch [2]
    Linux From Scratch [1]
  • 原文地址:https://www.cnblogs.com/JSZX11556/p/4548824.html
Copyright © 2020-2023  润新知