51nod 1649 齐头并进 (djikstra求最短路径,只用跑一次)
2024-08-31 12:34:00
题目:
这道题有一个坑点:两种交通工具同时出发,中途不能停留在同一个小镇。
其实想通了就很简单,因为要么火车一步到达,要么汽车一步到达。不可能停留在同一个地方。
可是我还WA了好几次,蠢哭。想用BFS写,一直TLE,后来想到这点之后,用djikstra求单源最短路径就出来了。
如果火车一步到,就求汽车的单源最短路径;如果汽车一步到,就求火车的单源最短路径。
代码:
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <set>
#include <math.h>
#include <queue>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef long long ll;
//#define INF 2147483647
#define INF 2000000000 int n,m;
#define MAX_V 410
int cost[MAX_V][MAX_V]; //cost[u][v]表示e = (u,v)的权值
int d[MAX_V]; //源点s出发的最短距离
bool used[MAX_V]; //标记使用过的点 int djikstra(){
fill(d,d+n+,INF);
fill(used,used+n,false);
d[] = ;
while(true){
int v = -;
for(int i = ;i <= n; i++){
if(!used[i]&&(v == - || d[i] < d[v])) v = i;
}
if(v == -) break; used[v] = true;
for(int i = ;i <= n; i++){
if(cost[v][i] == ){
d[i] = min(d[i],d[v]+cost[v][i]);
}
}
}
if(d[n] == INF) return -;
else return d[n];
} int main() {
cin >> n >> m;
for(int i = ;i <= n; i++){
for(int j = ;j <= n; j++){
cost[i][j] = -;
if(i == j) cost[i][j] = ;
}
}
for(int i = ;i <= m; i++){
int u,v;
cin >> u >> v;
cost[u][v] = ;
cost[v][u] = ;
} if(cost[][n] == ){
for(int i = ;i <= n; i++){
for(int j = ;j <= n; j++){
cost[i][j] = -cost[i][j];
}
}
}
cout << djikstra() << endl;
return ;
}
最新文章
- yii中的cookie的发送和读取
- TTAS Lock C++11 实现
- PHP加载另一个文件类的方法
- 慕课网-安卓工程师初养成-4-7 Java循环语句之 while
- 使用jquery实现局部刷新DIV
- [BZOJ 1150] [CTSC2007] 数据备份Backup 【贪心 + 链表】
- Date和TimeZone的关系
- 错误:This function has none of DETERMINISTIC... 的解决
- 记一次线上Zabbix对Redis监控实录
- mysql 数据库导出与导入
- JWT学习小结
- 自定义Windows右击菜单调用Winform程序
- docker-compose学习
- hdu多校1004 Distinct Values
- 测试教程网.unittest教程.6. 命令行接口
- python项目飞机大战
- css3 :nth-child()选择器的使用
- hdu 4888 最大流慢板
- maven 安装下载与配置 代理设置 《解决下载慢问题》
- php实践
热门文章
- BZOJ 2957 分块
- IE8不支持响应式设计解决方法
- Typescript 模拟实现 多继承
- dfs___刷题记录
- GFM(GitHub Flavored Markdown)与标准Markdown的语法区别
- Debian下的内核编译
- JS 数值转换、加减乘除
- How Many Partitions Does An RDD Have
- IOS - 6\7下UINavigationBar的颜色的方法改变 ——转载http://www.th7.cn/Program/IOS/201310/155057.shtml
- 报错:SyntaxError: Non-ASCII character &#39;\xe4&#39; in file