文章

迪杰斯特拉图论

迪杰斯特拉图论

迪杰斯特拉

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
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6+6;
const int M = 3e5+7;
#define ll long long
#define en '\n'
#define debug cout<<"------"
#define pii pair<int,int>
#define fast ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int dx[]={1,-1,0,0,1,1,-1,-1};
int dy[]={0,0,1,-1,1,-1,1,-1};
inline ll read()
{
    char c = getchar();ll x = 0,s = 1;
    while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}//是符号
    while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}//是数字
    return x*s;
}
inline void write(ll x) {
    if (x < 0) x = -x, putchar('-');
    if (x > 9) write(x/10);
    putchar('0'+x%10);
}
bool isprime(ll x)
{
    if(x<2||(x%2==0&&x>2))return 0;
    for(ll i=3;i<=x/i;i+=2)if(x%i==0)return 0;
    return 1;
}
ll qsm(ll x,ll y)
{
    ll ans=1;
    while(y)
    {
        if(y&1)ans=ans*x;
        x=x*x;
        y>>=1;
    }
    return ans;
}
priority_queue<pii, vector<pii>, greater<pii>> q;
vector<pii>v[N];
ll dist[N];
bool vis[N];

int main()
{
	int n,m;
	cin>>n>>m;
	for(int i=2;i<=n;i++)dist[i]=1e9;
	for(int i=1;i<=m;i++)
	{
		int a,b;
		ll w;
		cin>>a>>b>>w;
		v[a].emplace_back(make_pair(b,w));
		v[b].emplace_back(make_pair(a,w));
	}
	q.push(make_pair(0,1));
	while(q.size())
	{
		pii t=q.top();
		q.pop();
		int x=t.second;
		int w=t.first;
		if(vis[x])continue;
		vis[x]=1;
		for(auto i:v[x])
		{
			int xx=i.first;
			int ww=i.second;
			if(dist[xx]>dist[x]+ww)
			{
				
				dist[xx]=dist[x]+ww;
				q.push(make_pair(dist[xx],xx));
			}
		}
	}
	if(dist[n]>=1e9)cout<<"-1";
	else cout<<dist[n];
    return 0;
}
本文由作者按照 CC BY 4.0 进行授权