poj3613 Cow Relays
作者:互联网
题目
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
翻译
题目描述 给定T条边的无向图,点的编号为1~1000之间的整数。求从起点S到终点E恰好经过N条边(可重复)的最短路。2<=T<=100
2<=N<=1000000 输入 第一行输入四个数,分别表示N,T,S,E
以下T行分别表示每条路径w,a,b,w表示路径长度 输出 输出从S到T经过所有牛的最短路 样例输入
2 6 6 4 11 4 6 4 4 8 8 4 9 6 6 8 2 6 9 3 8 9样例输出
10
分析
由于N很大并且求的是“N最短路”所以:
但在写完之后你会发现编(zuo)号(zhe)是(te)乱(bie)的(hen),这时我们需要我们需要用到哈希。
代码
#include<iostream> #include<cstring> #include<algorithm> using namespace std; int n,t,s,e,a[1001][1001],o[1001][1001],ans[1001][1001],vis[1001],p[1001],number[1001],minn[1001][1001],num; inline int put(int x)//哈希 { if(!vis[x]) p[++num]=x,vis[x]=1,number[x]=num; return number[x]; } inline void floyd() { memcpy(minn,ans,sizeof(minn)); memset(ans,999999,sizeof(ans)); for(int k=1;k<=num;k++) for(int i=1;i<=num;i++) for(int j=1;j<=num;j++) ans[i][j]=min(minn[i][k]+a[k][j],ans[i][j]); } inline void change() { memcpy(o,a,sizeof(o)); memset(a,999999,sizeof(a)); for(int k=1;k<=num;k++) for(int i=1;i<=num;i++) for(int j=1;j<=num;j++) a[i][j]=min(o[i][k]+o[k][j],a[i][j]); } inline int sq(int b)//快速幂的精髓 { while(b) { if(b&1) floyd(); change(); b>>=1; } return ans[number[s]][number[e]]; } int main() { memset(a,999999,sizeof(a)); memset(ans,999999,sizeof(ans));//赋初值(这里本人建议用999999) cin>>n>>t>>s>>e; for(int i=1;i<=t;i++) { int x,y,z; cin>>z>>x>>y; a[put(y)][put(x)]=a[put(x)][put(y)]=z;//用哈希节约时间、空间 } for(int i=1;i<=num;i++) ans[i][i]=0;//自己到自己为0 cout<<sq(n); return 0; }
标签:cow,Cow,int,trails,poj3613,ans,intersections,Relays,1001 来源: https://www.cnblogs.com/chenjiaxuan/p/11068754.html