The Shortest Path Gym
来源:互联网 发布:php和js 编辑:程序博客网 时间:2024/06/04 23:23
https://vjudge.net/problem/Gym-101498L
题意 给你一个图 有可能存在负环 要求出权值最小路径 如果存在负环 则输出-inf
CF评测机强无敌。。。。 啥都能暴力都能过(数据太水?)
2500ms时限跑了2480ms。
思想就是暴力。
求任意两点之间最短路首先肯定是想到floyd 那么就是n^3复杂度。
然后其实边只有4000条,然后联想到用邻接表优化floyd。 然后我码力不行,写挫了,爆内存。。。。。
后面经大佬指点,可以尝试直接暴力。
先spfa求一遍最短路判负环,如果存在负环 直接输出-inf
然后对每个点进行一次dfs求最短路径。 (直接忽略换,因为正环对答案是没有贡献的,dfs碰到环的时候打个标记即可)
每次dfs最坏复杂度O(m) 要循环 n次 每次还要重新初始化记录数组
所以复杂度是O(n^2+n*m) 因该吧
第二种方法很玄学,
把所有边用邻接表存起来,然后依次递推重复n+1次。
for(int it=0;it<=n;it++) { for(int i=1;i<=n;i++) { for(int j=0;j<V[i].size();j++) { int v=V[i][j].v; int c=V[i][j].cost; int u=i; dis[u]=min(dis[u],dis[v]+c); ans=min(ans,dis[u]); } } }
重复n+1次是为了能让任意两个点之间的距离都变遍历到。。
就是动态规划思想,很玄学,讲不清楚。
最后在来次O(n+m)的遍历 找一下环。
每次遍历有m条边 所以复杂度为O(m) 遍历n+1次
所以总复杂度约为为O(n*m) 吧?
第一种方法只是理论AC 没具体实现
#include <algorithm>#include <cstdio>#include <cstring>#include<iostream>#include<string>#include <cstdlib>#include<queue>#include<set>using namespace std;const int MAX=1e6+5;long long dis[MAX];class node{public: long long cost; int v; node(int v,long long cost): v(v),cost(cost){}};vector<node> V[2005];long long maps[2005][2005];int main(){ int T; scanf("%d",&T); while(T--) { int n,m; scanf("%d %d",&n,&m); for(int i=0;i<=n;i++) { V[i].clear(); } for(int i=0;i<=n;i++) for(int j=0;j<=n;j++) maps[i][j]=MAX; int u,v; long long c; long long ans=MAX; for(int i=0;i<m;i++) { scanf("%d %d %lld",&u,&v,&c); ans=min(c,ans); V[v].push_back(node(u,c)); } if(ans>=0) { cout<<ans<<endl; continue; } int cir=0; for(int it=0;it<=n;it++) { for(int i=1;i<=n;i++) { for(int j=0;j<V[i].size();j++) { int v=V[i][j].v; int c=V[i][j].cost; int u=i; dis[u]=min(dis[u],dis[v]+c); ans=min(ans,dis[u]); } } } for(int i=1;i<=n&&cir==0;i++) { for(int j=0;j<V[i].size()&&cir==0;j++) { int v=V[i][j].v; int c=V[i][j].cost; int u=i; if(dis[u]>dis[v]+c) cir=1; } } if(cir) puts("-inf"); else cout<<ans<<endl; }}
阅读全文
0 0
- The Shortest Path Gym
- hdu2807---The Shortest Path
- hdu 2807 The Shortest Path
- hdu 2807 The Shortest Path
- hdu 2807 The Shortest Path
- HDU 2807 The Shortest Path
- HDU2807:The Shortest Path(Floyd)
- The shortest path-dp+tsp
- HDU 2224 The shortest path
- hdu 2224 The shortest path
- HDU 2807 The Shortest Path
- HDU 2224 The shortest path
- HDU 2224 The shortest path
- Shortest path of the king
- Shortest path of the king
- SPOJ-SHPATH - The Shortest Path
- HDU 2807 The Shortest Path
- HDU-2224-The shortest path
- 【python】完全自学笔记(速查手册)
- 【Java学习笔记之二十六】深入理解Java匿名内部类
- 新的开始,与大学告别
- 学习笔记
- 消息系统
- The Shortest Path Gym
- 汇总收集C/C++文件读写
- 凯撒密码 Caesar's code
- 小题总结
- 主成分分析(PCA)原理详解
- 不往高处走,你不知道自己能变得多优秀
- POJ
- NSTimer定时器的使用
- java 寻找数组中第k大的值