1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
#include<cstdio> #include<cstring> #include<queue> #include<iostream>
#define MAXN 200005 #define MAX_INT 2147483647
using namespace std;
int last[5005], dist_1[5005], dist_2[5005], n, m, gra[5005][5005]; bool mark[MAXN];
struct node { int u; int v; int w; int next; node() { u = v = w = next = 0; } }edge[MAXN];
void spfa( int dist[5005], int s ) { queue<int>myQueue; dist[s] = 0; memset(mark, false, sizeof(mark)); mark[s] = true; myQueue.push(s); while( !myQueue.empty() ) { int x = myQueue.front(); myQueue.pop(); mark[x] = false; int t = last[x]; while( t ) { if( dist[ edge[t].v ] > dist[x] + edge[t].w ) { dist[ edge[t].v ] = dist[x] + edge[t].w; if( !mark[ edge[t].v ] ) myQueue.push( edge[t].v ); } t = edge[t].next; } } }
int main() { cin >> n >> m; for(int i = 1;i <= m;i ++) { int a, b, c; scanf("%d %d %d", &a, &b, &c); edge[i].u = edge[i + m].v = a; edge[i].v = edge[i + m].u = b; edge[i].w = edge[i + m].w = c; edge[i].next = last[a]; last[a] = i; edge[i + m].next = last[b]; last[b] = i + m; } memset( dist_1, 1, sizeof(dist_1) ); spfa( dist_1, 1 ); memset( dist_2, 1, sizeof(dist_2) ); spfa( dist_2, n ); int ans = MAX_INT, tmp = MAX_INT; for(int i = 1;i <= n;i ++) { int t = last[i]; while( t ) { if( dist_1[i] + dist_2[ edge[t].v ] + edge[t].w < tmp ) { ans = tmp; tmp = dist_1[i] + dist_2[ edge[t].v ] + edge[t].w; } else if( dist_1[i] + dist_2[ edge[t].v ] + edge[t].w < ans && dist_1[i] + dist_2[ edge[t].v ] + edge[t].w != tmp ) ans = dist_1[i] + dist_2[ edge[t].v ] + edge[t].w; t = edge[t].next; } } cout << ans << endl; return 0; }
|