码迷,mamicode.com
首页 > 其他好文 > 详细

PKU 3613 Cow Relays (指定路径条数的最短路)

时间:2014-06-27 07:39:23      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   2014   string   



题意:N,T,S,E:给你T条边,每条边两端都有编号和权值,问从S走到E允许走N条边,求最短路。


foyld加矩阵快速幂思想。


注意要把边离散


#include <iostream>
#include <fstream>
#include <string.h>
#include <algorithm>
using namespace std;
#define M 303
#define inf 0x3fffffff
struct node
{
	int a[M][M];
	node()
	{
		for(int i=0;i<M;i++)
		{
			for(int j=0;j<M;j++)
				a[i][j]=inf;
		}
	}
};
int n,t,s,e;
int mp[1010],cnt;
node ma;
void foyld(node &a,node &b,node &c)
{
	node temp;
	for(int k=1;k<=cnt;k++)
	{
		for(int i=1;i<=cnt;i++)
		{
			for(int j=1;j<=cnt;j++)
				temp.a[i][j]=min(a.a[i][k]+b.a[k][j],temp.a[i][j]);
		}
	}
	for(int i=0;i<M;i++)
		for(int j=0;j<M;j++)
			c.a[i][j]=temp.a[i][j];
}
void pow()
{
	node ans;
	for(int i=0;i<M;i++) ans.a[i][i]=0;
	while(n)
	{
		if(n&1)
			foyld(ma,ans,ans);
		foyld(ma,ma,ma);
		n>>=1;
	}
	printf("%d\n",ans.a[mp[s]][mp[e]]);
}
int main()
{
	while(~scanf("%d%d%d%d",&n,&t,&s,&e))
	{
		int a,b,c;
		cnt=0;
		memset(mp,0,sizeof(mp));
		while(t--)
		{
			scanf("%d%d%d",&c,&a,&b);
			if(!mp[a]) mp[a]=++cnt;
			if(!mp[b]) mp[b]=++cnt;
			ma.a[mp[a]][mp[b]]=ma.a[mp[b]][mp[a]]=c;
		}
		pow();
	}
	return 0;
}


PKU 3613 Cow Relays (指定路径条数的最短路),布布扣,bubuko.com

PKU 3613 Cow Relays (指定路径条数的最短路)

标签:style   class   blog   code   2014   string   

原文地址:http://blog.csdn.net/u012861385/article/details/34926089

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!