1. 程式人生 > >奶牛接力 (Cow Relays, USACO 2007 Nov)

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

快速 perl esp separate 最短 scan art tin single

題目描述

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)