http://acm.hdu.edu.cn/showproblem.php?pid=1874
2013-12-01 12:47
323 查看
hdu的1874题
用flowd算法AC
代码如下:要注意输入边的判断。
#include <iostream> #define mx 999999 using namespace std; int edge[202][202] ; int a , b, x , s , t , n , m; int main() { while(cin >> n >> m) { for(int i = 0; i < n; i ++) for(int j = 0; j < n; j ++) edge[i][j] = mx ; for(int i = 0;i < m; i ++) { cin >> a >>b >> x ; if(edge[a][b] != mx) { if(edge[a][b] > x) edge[a][b] = edge[b][a] = x ; } else edge[a][b] = edge[b][a] = x ; } cin >> s >> t ; for(int k = 0; k < n; k ++) for(int i = 0; i < n; i ++) for(int j = 0; j < n; j ++) if(edge[i][j] > edge[i][k] + edge[k][j]) { edge[i][j] = edge[i][k] + edge[k][j] ; } if(s == t) cout << 0 << endl ; else if(edge[s][t] == mx) cout << -1 << endl; else cout << edge[s][t] << endl; } return 0 ; }
用dijkstra算法#include <iostream>#define mx 100000000using namespace std;int edge[202][202] ;int dist[202] ;int visit[202] ;int s , t , n , m , a , b , x ;void dijkstra(){ int index = -1; int miner = mx ; for(int i = 0; i < n; i ++) { if(!visit[i] && miner > dist[i]) { miner = dist[i] ; index = i ; } } if(index == -1) return ; visit[index] = 1 ; for(int i = 0; i < n; i ++) if(!visit[i] && dist[i] > dist[index] + edge[index][i]) { dist[i] = dist[index] + edge[index][i] ; } dijkstra(); //说来也不好意思,这句我老是忘记,导致我错了好多次,还发现不了。再接再厉!}void init(){ for(int i = 0; i < n; i ++) for(int j = 0; j < n; j ++) if(i == j) edge[i][j] = 0 ; else edge[i][j] = mx ; for(int i = 0; i < m; i ++) { cin >> a >> b >> x ; if(edge[a][b] > x) edge[a][b] = edge[b][a] = x ; }}int main(){ while(cin >> n >> m) { init() ; cin >> s >> t ; for(int i = 0; i < n; i ++) { visit[i] = 0; dist[i] = edge[s][i] ; } dist[s] = 0; visit[s] = 1 ; dijkstra(); if(dist[t] == mx) cout << -1 << endl ; else cout << dist[t] << endl; } return 0;}
相关文章推荐
- http://acm.hdu.edu.cn/showproblem.php?pid=1874
- http://acm.hdu.edu.cn/showproblem.php?pid=1874 简单题
- http://acm.hdu.edu.cn/showproblem.php?pid=1874。。
- 最短路径问题 多加了一个费用 http://acm.hdu.edu.cn/showproblem.php?pid=3790
- http://acm.hdu.edu.cn/showproblem.php?pid=1018
- http://acm.hdu.edu.cn/showproblem.php?pid=1394
- Number Sequence&&http://acm.hdu.edu.cn/showproblem.php?pid=1005
- http://acm.hdu.edu.cn/showproblem.php?pid=1541 结点更新求最左区间的个数
- http://acm.hdu.edu.cn/showproblem.php?pid=2688 数状数组 线段树
- http://acm.hdu.edu.cn/showproblem.php?pid=2446
- hdu 2099 整数的尾数 http://acm.hdu.edu.cn/showproblem.php?pid=2099
- http://acm.hdu.edu.cn/showproblem.php?pid=2612
- http://acm.hdu.edu.cn/webcontest/contest_showproblem.php?pid=1004&ojid=1&cid=6866&hide=1&problem=Pro
- A C&&http://acm.hdu.edu.cn/showproblem.php?pid=1570
- http://acm.hdu.edu.cn/webcontest/contest_showproblem.php?cid=963&pid=1019&ojid=1
- Advanced Fruits(链接:http://acm.hdu.edu.cn/showproblem.php?pid=1503)
- Encoding http://acm.hdu.edu.cn/showproblem.php?pid=1020
- 最小路径覆盖&&http://acm.hdu.edu.cn/showproblem.php?pid=4160
- http://acm.hdu.edu.cn/showproblem.php?pid=1005
- 分拆素数和(http://acm.hdu.edu.cn/showproblem.php?pid=2098)