http://poj.org/problem?id=3613
我们都知道如果单纯的求从s点到e点恰好经过k条边的路径数量。
就直接将01表进行k次幂即可。
那么如果是求最短路径长度呢。
那就是把邻接矩阵进行k次floyd即可。
具体解释比较复杂。记住即可。
k最大有1000000.
所以快速幂一下,只要将矩阵相乘那一段,改成floyd即可
真是奇妙。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#include<cmath>
#include<map>
using namespace std;
struct node{
int ma[111][111];
};
map<int,int>p;
int n,t,s,e;
int js;
node operator * (node x,node y)
{
node c;
memset(c.ma,0x3f3f3f,sizeof(c.ma));
for(int i=1;i<js;i++)
{
for(int j=1;j<js;j++)
{
for(int k=1;k<js;k++)
{
c.ma[j][k]=min(c.ma[j][k],x.ma[j][i]+y.ma[i][k]);
}
}
}
return c;
}
node qpow(node x,int k)
{
node ans=x;
k--;
while(k)
{
if(k&1)ans=ans*x;
x=x*x;
k>>=1;
}
return ans;
}
int main(){
while(cin>>n>>t>>s>>e)
{
js=1;
p.clear();
int st,ed,cost;
node a;
memset(a.ma,0x3f3f3f,sizeof(a.ma));
for(int i=0;i<t;i++)
{
cin>>cost>>st>>ed;
if(p[st]==0)
{
p[st]=js++;
}
if(p[ed]==0)
{
p[ed]=js++;
}
a.ma[p[st]][p[ed]]=a.ma[p[ed]][p[st]]=cost;
}
node ans=qpow(a,n);
cout<<ans.ma[p[s]][p[e]]<<endl;
}
return 0;
}