1.题目描述:
find the mincost route
Time Limit: 1000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 5112 Accepted Submission(s): 2055
Problem Description
杭州有N个景区,景区之间有一些双向的路来连接,现在8600想找一条旅游路线,这个路线从A点出发并且最后回到A点,假设经过的路线为V1,V2,....VK,V1,那么必须满足K>2,就是说至除了出发点以外至少要经过2个其他不同的景区,而且不能重复经过同一个景区。现在8600需要你帮他找一条这样的路线,并且花费越少越好。
Input
第一行是2个整数N和M(N <= 100, M <= 1000),代表景区的个数和道路的条数。
接下来的M行里,每行包括3个整数a,b,c.代表a和b之间有一条通路,并且需要花费c元(c <= 100)。
接下来的M行里,每行包括3个整数a,b,c.代表a和b之间有一条通路,并且需要花费c元(c <= 100)。
Output
对于每个测试实例,如果能找到这样一条路线的话,输出花费的最小值。如果找不到的话,输出"It's impossible.".
Sample Input
3 3 1 2 1 2 3 1 1 3 1 3 3 1 2 1 1 2 3 2 3 1
Sample Output
3 It's impossible.
Author
8600
Source
Recommend
8600
有出发有回来,而且要经过至少两个景区,单纯去构造spfa好像很难,可以回归floyd算法,注意到floyd最外层的k循环在循环到某个数ki时,前面以0到ki-1为中间结点的最短路径已经求出。
因此只要在内层的双循环之前再用一个双循环记录已找到的最小环的值即可。注意的地方是要开两个数组存图,一个图就表示原图,不能改变值,另一个用来记录最短路。
4.AC代码:
#include <bits/stdc++.h>
#define INF 0x1f1f1f1f
#define maxn 100100
#define N 111
#define eps 1e-6
#define pi acos(-1.0)
#define e exp(1.0)
using namespace std;
const int mod = 1e9 + 7;
typedef long long ll;
typedef unsigned long long ull;
int mp[N][N], dis[N][N];
int ans;
void floyd(int n)
{
for (int k = 1; k <= n; k++) // k is the max of ijk
{
for (int i = 1; i < k; i++)
for (int j = i + 1; j < k; j++)
ans = min(ans, dis[i][j] + mp[i][k] + mp[k][j]);
// find the shortest path
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j]);
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
long _begin_time = clock();
#endif
int n, m;
while (~scanf("%d%d", &n, &m))
{
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
{
if (i == j)
mp[i][j] = dis[i][j] = 0;
else
mp[i][j] = dis[i][j] = INF;
}
while (m--)
{
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
mp[u][v] = mp[v][u] = dis[u][v] = dis[v][u] = min(mp[u][v], w);
}
ans = INF;
floyd(n);
if (ans == INF)
puts("It's impossible.");
else
printf("%d\n", ans);
}
#ifndef ONLINE_JUDGE
long _end_time = clock();
printf("time = %ld ms.", _end_time - _begin_time);
#endif
return 0;
}