您的位置:首页 > 其它

POJ3613 Cow Relays

2016-07-12 22:35 288 查看

 

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 6726   Accepted: 2626

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

 

经过n条边的最短路径。

好像可以贪心,先找到一条最短路,然后随便找个最小环绕圈圈,我没有尝试。

 

使用了标准解法,矩阵乘法+倍增floyd

floyd是枚举k点,更新i到j的最短路径,更新后实际上就是从原本的走一条路到达更新成了走两条路到达。

根据这个思想,我们可以倍增跑floyd,就能得出走2^k条边从i到j的最短路径。

 

代码如下:(a[i]里存的就是走2^i条边的最短路邻接矩阵)

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
const int mxn=200;
int mp[2000],cnt=0;
int m;
struct edge{
int x,y;
int len;
}e[mxn];
struct M{
int v[200][200];
M(){memset(v,50,sizeof v);}
friend M operator *(M a,M b){
M c;
int i,j,k;
for(i=0;i<=m;i++)
for(j=0;j<=m;j++)
for(k=0;k<=m;k++){
c.v[i][j]=min(c.v[i][j],a.v[i][k]+b.v[k][j]);
}
return c;
}
}a[120];
int n,t,S,E;
int main(){
scanf("%d%d%d%d",&n,&t,&S,&E);
int i,j;
memset(mp,-1,sizeof mp);
int u,v;
for(i=1;i<=t;i++){
scanf("%d%d%d",&e[i].len,&u,&v);
if(mp[u]==-1)mp[u]=++cnt;
if(mp[v]==-1)mp[v]=++cnt;
e[i].x=mp[u];e[i].y=mp[v];
}
for(i=1;i<=t;i++){
int x=e[i].x;int y=e[i].y;
a[0].v[x][y]=a[0].v[y][x]=e[i].len;
}
if(mp[S]==-1)mp[S]=++cnt;
if(mp[E]==-1)mp[E]=++cnt;
m=cnt;
S=mp[S];E=mp[E];
for(i=1;i<=20;i++){//倍增
a[i]=a[i-1]*a[i-1];
}
M ans=a[0];
n--;
for(i=20;i>=0;i--){
if((1<<i)&n)ans=ans*a[i];
}
printf("%d\n",ans.v[S][E]);
return 0;
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: