Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 20995 | Accepted: 6994 |
Description
Input
Output
Sample Input
5 5 1 2 20 2 3 30 3 4 20 4 5 20 1 5 100
Sample Output
90
Hint
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; #define INF 99999999 int w[20010][20010]; int e[40010]; int u[20010]; int v[20010]; int d[20010]; int t, n; int main(){ int i, j, k, m, ww, x, y; int z; int cnt; while(cin >> t >> n){ cnt = 0; memset(v, 0, sizeof(v)); memset(d, 0, sizeof(d)); for(i = 1; i <= n; i ++) //预处理出发点到i点的距离 d[i] = (i == 1 ? 0 : INF); for(i = 0; i < t; i ++){ //输入的时候不用注意有重复的边 scanf("%d %d", &z, &y); scanf("%d", &w[z][y]); e[++cnt] = w[z][y]; u[cnt] = z; v[cnt] = y; e[++cnt] = w[z][y]; u[cnt] = y; v[cnt] = z; } for( k = 0; k < n - 1; k ++){ for(i = 1; i <= cnt; i ++){ x = u[i]; y = v[i]; if(d[x] < INF) if(d[y] > d[x] + e[i]) d[y] = d[x] + e[i]; } } cout << d[n] << endl; } return 0; }
#define INF 1 << 31 - 1 int t, n; int cnt; int lastshow[40010]; int d[40010]; struct edge{ int to; int wei; int next; }e[40010]; void insert(int a, int b, int c){ cnt ++; e[cnt].to = b; e[cnt].next = lastshow[a]; e[cnt].wei = c; lastshow[a] = cnt; } queue<int> q; bool inq[40010]; void bellmanford(){ memset(inq, false, sizeof(inq)); while(!q.empty()){ q.pop(); } q.push(1); //注意此处push的是一个起点 while(!q.empty()){ int x = q.front(); q.pop(); inq[x] = false; for(int i = lastshow[x]; i != -1; i = e[i].next){ if(d[e[i].to] > d[x] + e[i].wei){ d[e[i].to] = d[x] + e[i].wei; if(!inq[e[i].to]){ inq[e[i].to] = true; q.push(e[i].to); } } } } } int main(){ int i, j, k, m, ww, x, y; int z; int cnt; while(cin >> t >> n){ cnt = 0; memset(lastshow, -1, sizeof(lastshow)); for(i = 1; i <= n; i ++) //预处理出发点到i点的距离 d[i] = (i == 1 ? 0 : INF); for(i = 0; i < t; i ++){ //输入的时候不用注意有重复的边 int a, b, c; scanf("%d %d %d", &a, &b, &c); insert(a, b, c); insert(b, a, c); } bellmanford(); cout << d[n] << endl; } return 0; }