奶牛接力 (Cow Relays, USACO 2007 Nov)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了奶牛接力 (Cow Relays, USACO 2007 Nov)相关的知识,希望对你有一定的参考价值。

题目描述

For their physical fitness program, N (2 ≤ N ≤ 1,000,000) cows have decided to run a relay race using the T (2 ≤ T ≤ 100) cow trails throughout the pasture.

Each trail connects two different intersections (1 ≤ I1i ≤ 1,000; 1 ≤ I2i ≤ 1,000), each of which is the termination for at least two trails. The cows know the lengthi of each trail (1 ≤ lengthi  ≤ 1,000), the two intersections the trail connects, and they know that no two intersections are directly connected by two different trails. The trails form a structure known mathematically as a graph.

To run the relay, the N cows position themselves at various intersections (some intersections might have more than one cow). They must position themselves properly so that they can hand off the baton cow-by-cow and end up at the proper finishing place.

Write a program to help position the cows. Find the shortest path that connects the starting intersection (S) and the ending intersection (E) and traverses exactly N cow trails.

给出一张无向连通图,求S到E经过k条边的最短路。

输入输出格式

输入格式:

 

  • Line 1: Four space-separated integers: N, T, S, and E

  • Lines 2..T+1: Line i+1 describes trail i with three space-separated integers: lengthi , I1i , and I2i

 

输出格式:

 

  • Line 1: A single integer that is the shortest distance from intersection S to intersection E that traverses exactly N cow trails.

 

输入输出样例

输入样例#1:
2 6 6 4
11 4 6
4 4 8
8 4 9
6 6 8
2 6 9
3 8 9
输出样例#1:
10




题目大意,求一条从s到e的最短路径,保证路径上包含n条路径

参考国家集训队论文  矩阵乘法在信息学中的应用


对于一个矩阵做k次Floyd,所求得的最短路径包含k个点(不包括起点和终点)

这道题就需要对矩阵做n-1次Floyd,再用矩阵快速幂进行加速优化



#include<bits/stdc++.h>
using namespace std;
struct Matrix
{
    int m[205][205];
    Matrix(){memset(m,63,sizeof(m));}
};
int num;
Matrix operator *(Matrix a,Matrix b)
{
    Matrix ans;
    for(int k=1;k<=num;k++)
        for(int i=1;i<=num;i++)
            for(int j=1;j<=num;j++)
                    ans.m[i][j]=min(ans.m[i][j],a.m[i][k]+b.m[k][j]);
    return ans;
}
Matrix pow(Matrix a,int n)
{
    Matrix ans=a;
    while(n)
    {
        if(n&1) ans=ans*a;
        a=a*a;
        n>>=1;
    }
    return ans;
}
map<int,int>mp;
int main()
{
    int n,t,s,e;
    Matrix a;
    scanf("%d%d%d%d",&n,&t,&s,&e);
    for(int i=1,u,v,w;i<=t;i++)
    {
        scanf("%d%d%d",&w,&u,&v);
        if(mp[u]==0) mp[u]=++num;
        if(mp[v]==0) mp[v]=++num;
        if(w<a.m[mp[u]][mp[v]])
            a.m[mp[u]][mp[v]]=a.m[mp[v]][mp[u]]=w;
    }
    a=pow(a,n-1);
    printf("%d",a.m[mp[s]][mp[e]]);
}

 



以上是关于奶牛接力 (Cow Relays, USACO 2007 Nov)的主要内容,如果未能解决你的问题,请参考以下文章

[BZOJ] 1706: [usaco2007 Nov]relays 奶牛接力跑

BZOJ_[usaco2007 Nov]relays 奶牛接力跑_离散化+倍增弗洛伊德

[bzoj1706] [usaco2007 Nov]relays 奶牛接力跑

Floyd矩阵乘法BZOJ1706- [usaco2007 Nov]relays 奶牛接力跑

bzoj1706: [Usaco2007 Nov]relays 奶牛接力跑 (Floyd+新姿势)

zjoj1706: [usaco2007 Nov]relays 奶牛接力跑