最短路默写

dijkstra

注意:vector空间问题,以及正负权。

#include <bits/stdc++.h>
using namespace std;
const long long INF=999999999999999999;
int n,m,x,y,t=1;
long long dis[400001];
bool b[400001];
int head[400001];
struct st {
	int v;
	long long w;
	friend bool operator < (st a,st b)
	{
		return a.w>b.w;
	}
};
struct node{
	int x,y,z,next;
}a[2000001];
void add(int x,int y,int z)
{
	a[t].x=x;
	a[t].y=y;
	a[t].z=z;
	a[t].next=head[x];
	head[x]=t++;
}
priority_queue<st> q;
void di(int s) {
	q.push({s,0});
	while(!q.empty()) {
		int xx=q.top().v;
		q.pop();
		if(b[xx]) continue;
		if(xx==y) break;
		b[xx]=1;
		for(int it=head[xx];it;it=a[it].next) {
			int u=a[it].y,w=a[it].z;
			if(dis[u]>dis[xx]+w) {
				dis[u]=dis[xx]+w;
				q.push({u,dis[u]});
			}
		}
	}
}
signed main() {
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	scanf("%lld %lld",&n,&m);
	for(int i=1; i<=m; i++) {
		int a,b,c;
		scanf("%d %d %d",&a,&b,&c);
		add(a,b,c);
	}
	scanf("%lld %lld",&x,&y);
	for(int i=1; i<=n; i++) 
	{
		dis[i]=INF;
		b[i]=false;
	}
	dis[x]=0;
	di(x);
	for(int i=1;i<=n;i++) printf("%lld ",dis[i]);
	return 0;
}

spfa

不要卡我 spfa 啊啊啊,spfa 唯一真神。

#include <bits/stdc++.h>
#define int long long
#define endl "\n"
using namespace std;
int n,m,s;
int dis[100001],b[100001];
struct st {
	int v,w;
};
vector<st> v[100001];
queue<int> q;
void spfa(int s) {
	q.push(s);
	b[s]=1;
	while(!q.empty()) {
		int x=q.front();
		q.pop();
		b[x]=0;
		for(auto it:v[x]) {
			int u=it.v,w=it.w;
			if(dis[u]>dis[x]+w) {
				dis[u]=dis[x]+w;
				if(!b[u]) {
					q.push(u);
					b[u]=1;
				}
			}
		}
	}
}
signed main() {
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>m>>s;
	for(int i=1; i<=m; i++) {
		int a,b,c;
		cin>>a>>b>>c;
		v[a].push_back({b,c});
	}
	for(int i=1; i<=n; i++) dis[i]=2147483647;
	dis[s]=0;
	spfa(s);
	for(int i=1; i<=n; i++) cout<<dis[i]<<" ";
	return 0;
}
posted @ 2024-11-03 21:22  yaaaaaan  阅读(13)  评论(1编辑  收藏  举报