XTU 1179 Shortest Path
来源:互联网 发布:淘宝客乱扣佣金 编辑:程序博客网 时间:2024/05/29 13:33
Shortest Path
[ Submit Code ] [ Top 20 Runs ] Acceteped : 56 Submit : 223 Time Limit : 5000 MS Memory Limit : 65536 KBDescription
题目描述
N(3≤N≤1,000)个城市(编号从1~N),M(N-1≤M≤10,000)条公路连接这些城市,每条公路都是双向通车的。 你想从1号城市出发,到达N号城市,期间你希望通过按顺序经过K(0≤K≤3)个指定的城市(这K+2个城市只允许达到1次),求最短的里程。
输入
存在多个样例。 每个样例的第一行是三个整数N,M,K。如果N,M,K为0,则表示输入结束。 以后是M行表示M条公路,每行三个整数x(1≤x≤N),y(1≤y≤N),c(1≤c≤1,000),表示城市x与城市y之间有一条距离为c的公路。输入保证任意两座城市之间至少存在一条路。然后的一行包含K个城市的序号,序号属于[2,N-1]。
输出
每行输出一个样例的结果,为一个整数。如果不存在这样的方案,输出“Impossible”。
样例输入
3 3 1
1 2 3
2 3 4
1 3 2
2
0 0 0
样例输出
7
Sample Input
Sample Output
Source
[ Submit Code ] [ Top 20 Runs ]
思路:最短路问题。因为被要求的几个城市只能去一次,所以在求最短路的时候,只要将其屏蔽掉即可,详见代码。
AC代码如下:
#include <bits/stdc++.h>using namespace std;const int maxn = 1005;const int inf = 0x3f3f3f3f;int w[maxn][maxn];int d[maxn], city[5];bool vis[maxn];int n, m, k;void dijkstra(int s, int t){ for (int i=1; i<=n; ++i) vis[i] = false; for (int i=1; i<=n; ++i) d[i] = w[s][i]; for (int i=0; i<=k+1; ++i) if (city[i]!=s && city[i]!=t) vis[city[i]] = true; for (int i=1; i<=n; ++i){ int mi=inf, x=1; for (int y=1; y<=n; ++y) if (!vis[y] && d[y]<=mi) mi = d[x=y]; if (mi == inf) break; vis[x] = true; for (int y=1; y<=n; ++y) if (!vis[y] && d[x]+w[x][y]<d[y]) d[y] = d[x]+w[x][y]; }}int main(){ ios::sync_with_stdio(false); cin.tie(0); while (~scanf("%d%d%d", &n, &m, &k) && n+m+k){ for (int i=1; i<=n; ++i) for (int j=1; j<=n; ++j){ if (i != j) w[i][j] = inf; else w[i][j] = 0; } int x, y, c; while (m--){ scanf("%d%d%d", &x, &y, &c); if (c < w[x][y]) w[x][y] = w[y][x] = c; } city[0] = 1; city[k+1] = n; for (int i=1; i<=k; ++i) scanf("%d", city+i); int ans = 0; bool ok = true; for (int i=0; i<=k; ++i){ dijkstra(city[i], city[i+1]); if (d[city[i+1]] == inf){ ok = false; break; } ans += d[city[i+1]]; } if (ok) printf("%d\n", ans); else printf("Impossible\n"); } return 0;}
1 0
- XTU 1179 Shortest Path
- Shortest Path
- Shortest Path
- Shortest Path
- hdoj 3631 Shortest Path
- hdu 3631 Shortest Path
- HDU3631 Shortest Path
- hdoj 3631 Shortest Path
- hdu 3631 Shortest Path
- hdu 3631 Shortest Path
- Hdu 3631 Shortest Path
- HDU3631:Shortest Path(Floyd)
- Shortest Path Faster Algorithm
- Dijkstra Shortest Path
- HDU 3631 Shortest Path
- HDU Shortest path
- HDU3631 Shortest Path 【Floyd】
- HDU3631:Shortest Path(Floyd)
- python【1】Python中常用的快捷键和BIF
- Java SE 6.0学习笔记——面向对象
- BurpSuite抓HTTPS数据
- JavaWeb防止表单重复提交
- 线性表--顺序储存结构 java实现
- XTU 1179 Shortest Path
- 在Google Chrome中快速解除网页屏蔽鼠标右键、复制等限制
- BigDecimal类的加减乘除
- 环境搭建基础知识0(Word无法切换中文输入法的解决方法)
- 正则中需要转义的特殊字符小结
- CSS 之 display:table
- Oracle获取时间或者月份列表
- Java基本数据类型
- Ajax导出Excel的做法流程