概述
Cow Relays
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 8810 | Accepted: 3474 |
Description
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.
Input
* 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
Output
* Line 1: A single integer that is the shortest distance from intersection S to intersection E that traverses exactly N cow trails.
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
Source
USACO 2007 November Gold
#include<cstdio>
#include<algorithm>
#include<cstring>
#define INF 0x3f3f3f3f
#define MAXN 210
using namespace std;
int Hash[1010];
int tn=0;
int n,t,s,e;
//本题的意思就是:经过k条边的最短路径
//本题的k就是n了,n头牛的数目
//倍增优化+快速幂
struct Matrix //矩阵乘法floyd
{
int a[MAXN][MAXN];
Matrix operator *(const Matrix &x) const
{
Matrix c;
memset(c.a,INF,sizeof(c.a));
for (int k=1;k<=tn;k++)
for (int i=1;i<=tn;++i)
for (int j=1; j<=tn; ++j) //这个是单步Floyd,一次插入一个点
c.a[i][j] = min(c.a[i][j],a[i][k]+x.a[k][j]); //矩阵乘法Floyd与正常的区别:
//1.没有对原数组进行更新,即原来的两点距离并没有改变
return c; //由第一点的区别可以推出第二点的区别
//2.一定是加一个点,添一条边
//一般的Floyd可能加一个点,添多条边,因为他不断dp,记录了之前的最优
//而最优可能不是两点的直接路径,有可能是加点的转达,这样就造成了
//加一个点添多条边
}
}str,ans;
void pow_mod()
{
ans=str; //插入n-1个点,求到的则是经过n条边的最短路径
n--; //n--是意思算str^(n-1)次方吧
while(n!=0)
{
if((n&1)==1)
ans=ans*str;
str=str*str;
n>>=1;
}
}
int main()
{
scanf("%d%d%d%d",&n,&t,&s,&e);
memset(str.a,INF,sizeof(str.a));
int i;
for(i=1;i<=t;i++)
{ //顶点的上限是10^3,但立方的话,也还是会超。
//但发现边只有最多100条
int x,y,w; //最多有200个点可以用,所以才想到hash压缩下
scanf("%d%d%d",&w,&x,&y);
if (!Hash[x]) Hash[x]=++tn; //这也就是邻接矩阵的离散吧,离散不是可以用邻接表吗,因为Floyd不是邻接表的数据结构
if (!Hash[y]) Hash[y]=++tn;
str.a[Hash[x]][Hash[y]]=str.a[Hash[y]][Hash[x]]=w;
}
pow_mod();
printf("%d",ans.a[Hash[s]][Hash[e]]);
return 0;
}
最后
以上就是悲凉丝袜为你收集整理的POJ-3613 Cow Relays (矩阵乘法Floyd+倍增思想快速幂)的全部内容,希望文章能够帮你解决POJ-3613 Cow Relays (矩阵乘法Floyd+倍增思想快速幂)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复