[倍增Floyd] BZOJ 1706 [usaco2007 Nov]relays 奶牛接力跑

题目大意:求s到t 长度为n 的最短路


裸的倍增Floyd


#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
using namespace std;

inline char nc()
{
	static char buf[100000],*p1=buf,*p2=buf;
	if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; }
	return *p1++;
}

inline void read(int &x)
{
	char c=nc(),b=1;
	for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
	for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;
}

const int N=205;

struct edge{
	int u,v,w;
}G[N];

int n,m,S,T;
int f[N][N],h[N][N],tmp[N][N];
int sx[N],icnt;

inline int Bin(int x){
	return lower_bound(sx+1,sx+icnt+1,x)-sx;
}

int main()
{
	freopen("t.in","r",stdin);
	freopen("t.out","w",stdout);
	read(n); read(m); read(S); read(T);
	for (int i=1;i<=m;i++)
		read(G[i].w),read(G[i].u),read(G[i].v),sx[++icnt]=G[i].u,sx[++icnt]=G[i].v;
	sort(sx+1,sx+icnt+1);
	icnt=unique(sx+1,sx+icnt+1)-sx-1;
	for (int i=1;i<=m;i++)
		G[i].u=Bin(G[i].u),G[i].v=Bin(G[i].v);
	memset(f,0x3f,sizeof(f));
	memset(h,0x3f,sizeof(h));
	for (int i=1;i<=icnt;i++)
		h[i][i]=0;
	for (int i=1;i<=m;i++)
		f[G[i].u][G[i].v]=f[G[i].v][G[i].u]=G[i].w;
	for (int t=0;(1<<t)<=n;t++)
	{
		if (n&(1<<t))
		{
			memset(tmp,0x3f,sizeof(tmp));
			for (int k=1;k<=icnt;k++)
				for (int i=1;i<=icnt;i++)
					for (int j=1;j<=icnt;j++)
						tmp[i][j]=min(tmp[i][j],h[i][k]+f[k][j]);
			memcpy(h,tmp,sizeof(tmp));
		}
		memset(tmp,0x3f,sizeof(tmp));
		for (int k=1;k<=icnt;k++)
			for (int i=1;i<=icnt;i++)
				for (int j=1;j<=icnt;j++)
					tmp[i][j]=min(tmp[i][j],f[i][k]+f[k][j]);
		memcpy(f,tmp,sizeof(tmp));
	}
	printf("%d\n",h[Bin(S)][Bin(T)]);
	return 0;
}


你可能感兴趣的:([倍增Floyd] BZOJ 1706 [usaco2007 Nov]relays 奶牛接力跑)