106832024-04-07 21:43:13999Nagysebességű vasútcpp17Accepted 100/100372ms48500 KiB
// Source: https://usaco.guide/general/io

#include <bits/stdc++.h>
#include <queue>
using namespace std;
#define int long long

signed main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int n,m;cin>>n>>m;
	vector<vector<pair<int,int>>> v(n);
	for(int i = 0;i<m;i++){
		int a,b,c;
		cin>>a>>b>>c;
		v[a].push_back({b,c});
		v[b].push_back({a,c});
	}
	vector<int> disS(n,LLONG_MAX),disE(n,LLONG_MAX),os(n,-1);
	priority_queue<pair<int, int>,vector<pair<int,int>>,greater<pair<int,int>>> q;
	disS[0]=0;
	disE[n-1]=0;
	q.push({0,0});
	vector<bool> proc1(n),proc2(n);
	while(!q.empty()){
		int a=q.top().second;
		q.pop();
		if(proc1[a])continue;
		proc1[a]=true;
		for(auto u:v[a]){
			int b=u.first,w=u.second;
			if(disS[b]>disS[a]+w){
				disS[b]=disS[a]+w;
				q.push({disS[b],b});
				os[b]=a;
			}
		}
	}
	vector<bool> shortestPath(n);
    int curr = n-1;
    while(curr!=-1) {
        shortestPath[curr]=true;
        curr=os[curr];
    }
	q.push({0,n-1});
	while(!q.empty()){
		int a=q.top().second;
		q.pop();
		if(proc2[a])continue;
		proc2[a]=true;
		for(auto u:v[a]){
			int b=u.first,w=u.second;
			if(disE[b]>disE[a]+w){
				disE[b]=disE[a]+w;
				q.push({disE[b],b});
			}
		}
	}
	int ans=INT_MAX;
	for(int i = 0;i<n;i++){
		for(auto u : v[i]){
			int a=i,b=u.first,c=u.second;
			if(disS[a]+disE[b]+c>disS[n-1]){
				if(disS[a]+disE[b]+c-disS[n-1]+1<c&&!(shortestPath[a]&&shortestPath[b])){//cout<<a<<' '<<b<<endl;
					ans=min(ans,disS[a]+disE[b]+c-disS[n-1]+1);
				}
			}
			if(disS[b]+disE[a]+c>disS[n-1]){
				if(disS[b]+disE[a]+c-disS[n-1]+1<c&&!(shortestPath[a]&&shortestPath[b])){//cout<<a<<' '<<b<<endl;
					ans=min(ans,disS[b]+disE[a]+c-disS[n-1]+1);
				}
			}
		}
	}cout<<(ans==INT_MAX?-1:ans)<<endl;
}
SubtaskSumTestVerdictTimeMemory
subtask10/0
1Accepted3ms1832 KiB
2Accepted3ms2056 KiB
subtask235/35
3Accepted4ms2680 KiB
4Accepted4ms2768 KiB
5Accepted4ms2816 KiB
6Accepted4ms2952 KiB
7Accepted4ms2972 KiB
8Accepted4ms3084 KiB
subtask330/30
9Accepted93ms23096 KiB
10Accepted92ms23412 KiB
11Accepted86ms23488 KiB
12Accepted93ms23584 KiB
13Accepted94ms23340 KiB
14Accepted97ms23488 KiB
subtask435/35
15Accepted349ms47880 KiB
16Accepted349ms48024 KiB
17Accepted351ms47884 KiB
18Accepted317ms48264 KiB
19Accepted370ms48084 KiB
20Accepted367ms48500 KiB
21Accepted337ms48412 KiB
22Accepted372ms48344 KiB
23Accepted338ms48484 KiB
24Accepted166ms31204 KiB
25Accepted94ms24348 KiB
26Accepted94ms24572 KiB
27Accepted94ms24648 KiB