POJ 1734 Sightseeing trip

题目大意:

求一个最小环。

用Floyd 求最小环算法。

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <cstring>
using namespace std;
#define INF 0xfffffff
#define maxn 260 int G[maxn][maxn], dist[maxn][maxn];
int Pre[maxn][maxn], Path[maxn];
int m, n, CrossNum = ; void SearchPath(int Star,int End)
{
while(Star != End)
{
Path[CrossNum ++] = Star;
Star = Pre[Star][End];
}
Path[CrossNum ++] = Star;
} void Floyd()
{
int MinLoop = INF;
for(int k=; k<=n; k++)
{
for(int i=; i<k; i++)
{
for(int j=i+; j<k; j++)
{
if( dist[i][j] + G[i][k] + G[k][j] < MinLoop )
{
MinLoop = dist[i][j] + G[i][k] + G[k][j];
CrossNum = ;
SearchPath(i,j);
Path[CrossNum++] = k;
}
}
} for(int i=; i<=n; i++)
{
for(int j=; j<=n; j++)
{
if(dist[i][j] > dist[i][k] + dist[k][j])
{
dist[i][j] = dist[i][k] + dist[k][j];
Pre[i][j] = Pre[i][k];
}
}
}
}
}
void Init()
{
for(int i=; i<=n; i++)
{
for(int j=; j<=n; j++)
{
dist[i][j] = G[i][j] = INF;
Pre[i][j] = j;
CrossNum = ;
}
}
} int main()
{
while(cin >> n >> m)
{ Init(); for(int i=; i<m; i++)
{
int a, b, c; cin >> a >> b >> c; G[a][b] = G[b][a] = dist[a][b] = dist[b][a] = min(dist[a][b], c);
} Floyd(); if( CrossNum)
{ for(int i=; i<CrossNum - ; i++)
{
printf("%d ", Path[i]);
}
printf("%d\n", Path[CrossNum - ]);
}
else
cout <<"No solution." << endl;
}
return ;
}
上一篇:Android Scroller类的详细分析


下一篇:五分钟了解Hash算法