标签:mem code badge max star trail off orm 输入输出格式
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.
2 6 6 4 11 4 6 4 4 8 8 4 9 6 6 8 2 6 9 3 8 9
10
程序:
//洛谷2886 //(1)对角线不能设置为0,否则容易自循环。(2)数组要放在主程序外面 //(3)K条边,不一定是最简路 #include<iostream> #include<cstdio> #include<map> #include<cstring> using namespace std; map<int,int>f; const int maxn=210; int k,t,s,e,n; int a[maxn][maxn]; struct Matrix{ int b[maxn][maxn]; }; Matrix A,S; Matrix operator *(Matrix A,Matrix B){//运算符重载 Matrix c; memset(c.b,127/3,sizeof(c.b) ); for(int k=1;k<=n;k++) for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) c.b[i][j]=min(c.b[i][j],A.b[i][k]+B.b[k][j]); return c; } Matrix power(Matrix A,int k){ if(k==0) return A; Matrix S=A; for(int i=1;i<=n;i++){ for (int j=1;j<=n;j++) cout<<A.b[i][j]<<" "; cout<<endl; } cout<<endl; while(k){ if(k&1)S=S*A;//奇数执行,偶数不执行 /*cout<<k<<":"<<endl; for(int i=1;i<=n;i++){ for (int j=1;j<=n;j++) cout<<S.b[i][j]<<" "; cout<<endl; }*/ cout<<endl; A=A*A; k=k>>1; } return S; } int main(){ cin>>k>>t>>s>>e; int w,x,y; memset(A.b,127/3,sizeof(A.b) );// 赋初值 n=0; for(int i=1;i<=t;i++){//t<100,x<1000 点不是从1开始的,可以用map离散化,给点从一开始编号。n记录共有多少个点。 cin>>w>>x>>y; if (f[x]==0) f[x]=++n; if (f[y]==0) f[y]=++n; A.b[f[x]][f[y]]=A.b[f[y]][f[x]]=min(w,A.b[f[y]][f[x]]); } S=power(A,k-1); s=f[s]; e=f[e]; cout<<S.b[s][e]; return 0; }
P2886 [USACO07NOV]牛继电器Cow Relays
标签:mem code badge max star trail off orm 输入输出格式
原文地址:https://www.cnblogs.com/ssfzmfy/p/10740803.html