//poj3613 给定起点终点,求经过k条边的最短路
//矩阵乘法 快速幂
//详见 俞华程 矩阵乘法在信息学中的应用 
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <map>
using namespace std;
#define ll long long 
#define fr(i,a,b) for(int i=a;i<=b;i++)
#define frr(i,a,b) for(int i=a;i>=b;i--)
#define ms(a,b) memset(a,b,sizeof(a))
#define scfd(a) scanf("%d",a)
#define scflf(a) scanf("%lf",a)
#define scfs(a) scanf("%s",a)
#define ptfd(a) printf("%d\n",a)
#define ptfs(a) printf("%s\n",a)
#define showd(a,b) printf(a"=%d\n",b)
#define showlf(a,b) printf(a"=%lf\n",b)
#define shows(a,b) printf(a"=%s\n",b)
#define mmcp(a,b) memcpy(a,b,sizeof(b))
#define pb(a) push_back(a)
const int MAXN=105;
const int MAXM=100005;
const ll INF=214748364555555LL;
int n,e,s,t,ed;
map<int,int>m;
struct matrix{
	ll n[MAXN][MAXN];
	matrix(){
		fr(i,0,MAXN-1)
			fr(j,0,MAXN-1)
				n[i][j]=INF;
	}
	matrix operator*(const matrix a){
		matrix ans;
		fr(i,0,ed-1)
			fr(j,0,ed-1)
				fr(k,0,ed-1)
					ans.n[i][j]=min(ans.n[i][j],n[i][k]+a.n[k][j]);
		return ans;
	}
}g;
int main(){
	//ios::sync_with_stdio(false);
	scanf("%d%d%d%d",&n,&e,&s,&t);
	fr(i,1,e){
		ll a;
		int b,c;
		scanf("%lld%d%d",&a,&b,&c);
		if(!m.count(b))
			m[b]=ed++;
		if(!m.count(c))
			m[c]=ed++;
		//g.n[m[c]][m[c]]=g.n[m[b]][m[b]]=0;
		g.n[m[c]][m[b]]=g.n[m[b]][m[c]]=a;
	}
	matrix ans;
	//fr(i,0,ed-1)
	//	ans.n[i][i]=0;
	ans=g;
	n--;
	while(n){
		if(n%2)
			ans=ans*g;
		g=g*g;
		n/=2;
	}
	cout<<ans.n[m[s]][m[t]]<<endl;
	return 0;
}
 posted on 2017-09-22 16:54  cylcy  阅读(132)  评论(0编辑  收藏  举报