BZOJ1599 find the mincost route 【floyd】

题目链接

BZOJ1599

题解

最小环模板?周末了养生一下【逃】

解释一下原理

\(floyd\)算法每一轮求出以\([1,k]\)为中介点的最短路

我们对于一个环,考虑环上编号最大的点,在\(k\)枚举到那个点时,\(k\)两边的点之间不经过\(k\)的最短路已经计算出来,相连接便是一个环

容易发现最小的环一定会被计算

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<map>
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define mp(a,b) make_pair<int,int>(a,b)
#define cls(s) memset(s,0,sizeof(s))
#define cp pair<int,int>
#define LL long long int
using namespace std;
const int maxn = 105,maxm = 100005,INF = 100000000;
inline int read(){
int out = 0,flag = 1; char c = getchar();
while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
return out * flag;
}
int n,m,G[maxn][maxn],d[maxn][maxn],minc;
void floyd(){
REP(i,n) REP(j,n) d[i][j] = G[i][j];
REP(k,n){
for (int i = 1; i < k; i++)
for (int j = i + 1; j < k; j++)
minc = min(minc,d[i][j] + G[j][k] + G[k][i]);
REP(i,n) REP(j,n) d[i][j] = min(d[i][j],d[i][k] + d[k][j]);
}
}
int main(){
while (~scanf("%d%d",&n,&m)){
REP(i,n) REP(j,n) G[i][j] = INF;
int a,b,w; minc = INF;
while (m--){
a = read(); b = read(); w = read();
if (G[a][b] > w) G[a][b] = G[b][a] = w;
}
floyd();
if (minc >= INF) puts("It's impossible.");
else printf("%d\n",minc);
}
return 0;
}
上一篇:SPRING+JNDI+C3P0 in tomcat6


下一篇:springMVC简单的一些操作