bzoj 1706 [usaco2007 Nov]relays 奶牛接力跑

[usaco2007 Nov]relays 奶牛接力跑

Time Limit: 5 Sec  Memory Limit: 64 MB
Submit: 744  Solved: 393
[Submit][Status][Discuss]

Description

FJ的N(2 <= N <= 1,000,000)头奶牛选择了接力跑作为她们的日常锻炼项目。至于进行接力跑的地点 自然是在牧场中现有的T(2 <= T <= 100)条跑道上。 农场上的跑道有一些交汇点,每条跑道都连结了两个不同的交汇点 I1_i和I2_i(1 <= I1_i <= 1,000; 1 <= I2_i <= 1,000)。每个交汇点都是至少两条跑道的端点。 奶牛们知道每条跑道的长度length_i(1 <= length_i <= 1,000),以及每条跑道连结的交汇点的编号 并且,没有哪两个交汇点由两条不同的跑道直接相连。你可以认为这些交汇点和跑道构成了一张图。 为了完成一场接力跑,所有N头奶牛在跑步开始之前都要站在某个交汇点上(有些交汇点上可能站着不只1头奶牛)。当然,她们的站位要保证她们能够将接力棒顺次传递,并且最后持棒的奶牛要停在预设的终点。 你的任务是,写一个程序,计算在接力跑的起点(S)和终点(E)确定的情况下,奶牛们跑步路径可能的最小总长度。显然,这条路径必须恰好经过N条跑道。

Input

* 第1行: 4个用空格隔开的整数:N,T,S,以及E

* 第2..T+1行: 第i+1为3个以空格隔开的整数:length_i,I1_i,以及I2_i, 描述了第i条跑道。

Output

* 第1行: 输出1个正整数,表示起点为S、终点为E,并且恰好经过N条跑道的路 径的最小长度

Sample Input

2 6 6 4
11 4 6
4 4 8
8 4 9
6 6 8
2 6 9
3 8 9

Sample Output

10

HINT

 

Source

Gold

 

挺好的一道题目

首先题目中只有100条边,却给出了10000个点(实际上最多只能有200个),离散化一下。

后面就是Floyd的新姿势,以前看过的集训队论文里面有:D

一开始的邻接矩阵是经过一条边的最短路,把这个邻接矩阵记作f[0]

f[1]=f[0]*f[0]=f[0]^2(这里的乘法是矩阵乘法),就可以表示恰巧经过两条边的啦。

f[2]=f[1]*f[0]=f[0]^3,恰巧表示经过两条边。

……

所以恰巧经过n条边的最短路是f[n-1]=f[0]^n。

矩阵快速幂一下就好啦。

注意看代码

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int MAXM=200+5;
 5 const int MAXN=1000+50;
 6 const ll INF=1e16;
 7 struct node
 8 {
 9     ll dis[MAXM][MAXM];
10 }f,result,origin;
11 int id[MAXN],cnt;
12 int n,t,s,e;
13 
14 node operator * (node a,node b)
15 {
16     node c;
17     for (int i=1;i<=cnt;i++)
18         for (int j=1;j<=cnt;j++) c.dis[i][j]=INF;
19     for (int k=1;k<=cnt;k++)
20         for (int i=1;i<=cnt;i++)
21             for (int j=1;j<=cnt;j++)
22                 c.dis[i][j]=min(c.dis[i][j],a.dis[i][k]+b.dis[k][j]);
23     return c;
24 }
25 
26 int getnum(int x)
27 {
28     if (id[x]==-1) 
29     {
30         id[x]=++cnt;
31         return(cnt);
32     }
33     else return(id[x]);
34 }
35 void init()
36 {
37     memset(id,-1,sizeof(id));
38     cnt=0;
39     scanf("%d%d%d%d",&n,&t,&s,&e);
40     memset(f.dis,0,sizeof(f.dis));
41     for (int i=1;i<=t;i++)
42     {
43         int u,v,w;
44         scanf("%d%d%d",&w,&u,&v);
45         u=getnum(u);
46         v=getnum(v);
47         f.dis[u][v]=f.dis[v][u]=w;
48     }
49     for (int i=1;i<=cnt;i++)
50         for (int j=1;j<=cnt;j++) if (!f.dis[i][j]) f.dis[i][j]=INF;
51 } 
52 int main()
53 {
54     init();
55     int k=n-1;
56     result=f,origin=f;
57     while (k)
58     {
59         if (k&1) result=result*origin;
60         k>>=1;
61         origin=origin*origin;
62     }
63     printf("%lld",result.dis[id[s]][id[e]]); 
64 }

 

posted @ 2017-12-24 16:41  Kaiser-  阅读(240)  评论(0编辑  收藏  举报