POJ 3613 Cow Relays (floyd+快速幂)

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值