分层最短路

dijkstra

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
int n,m,k;
int h[maxn],nxt[maxn],to[maxn],w[maxn],tot;
int dis[maxn][30];
bool v[maxn][30];
struct node
{
	int x,t,dis;
	bool operator < (const node nd) const
	{
		if (nd.dis == dis) return t>nd.t;
		else return dis>nd.dis;
	}
};
priority_queue<node> q;
void add(int x,int y,int z)
{
	tot++;
	to[tot]=y;
	nxt[tot]=h[x];
	w[tot]=z;
	h[x]=tot;
}
void dijkstra(int x)
{
	memset(dis,0x3f,sizeof(dis));
	dis[x][0]=0;
	q.push({x,0,0});
	while (q.size())
	{
		x=q.top().x;
		int t=q.top().t;
		q.pop();
		if (v[x][t]) continue;
		v[x][t] = true;
		for (int i=h[x];i;i=nxt[i])
		{
			int y=to[i];
			if (dis[y][t]>dis[x][t]+w[i])
			{
				dis[y][t]=dis[x][t]+w[i];
				q.push({y,t,dis[y][t]});
			}
			if (t<k)
			{
				if (dis[y][t+1]>dis[x][t])
				{
					dis[y][t+1]=dis[x][t];
					q.push({y,t+1,dis[y][t+1]});
				}
			}
		}
	}
}
int main()
{
	cin >> n >> m >> k;
	for (int i=1;i<=m;i++)
	{
		int x,y,z;
		cin >> x >> y >> z;
		add(x,y,z);
		add(y,x,z);
	}
	dijkstra(1);
	cout << dis[n][k] << endl;
	return 0;
}

spfa

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
int n,m,k;
int h[maxn],nxt[maxn],to[maxn],w[maxn],tot;
int dis[maxn][30];
bool v[maxn][30];
queue<pair<int,int>> q;
void add(int x,int y,int z)
{
	tot++;
	to[tot]=y;
	nxt[tot]=h[x];
	w[tot]=z;
	h[x]=tot;
}
void spfa(int x)
{
	memset(dis,0x3f,sizeof(dis));
	dis[x][0]=0;
	q.push(make_pair(x,0));
	while(q.size())
	{
		x=q.front().first;
		int t=q.front().second;
		q.pop();
		for(int i=h[x];i;i=nxt[i])
		{
			int y=to[i];
			if(dis[y][t]>dis[x][t]+w[i])
			{
				dis[y][t]=dis[x][t]+w[i];
				q.push(make_pair(y,t));
			}
			if (t<k)
			{
				if (dis[y][t+1]>dis[x][t])
				{
					dis[y][t+1]=dis[x][t];
					q.push(make_pair(y,t+1));
				}
			}
		}
	}
}
int main()
{
	cin >> n >> m >> k;
	for (int i=1;i<=m;i++)
	{
		int x,y,z;
		cin >> x >> y >> z;
		add(x,y,z);
		add(y,x,z);
	}
	spfa(1);
	cout << dis[n][k] << endl;
	return 0;
}
posted @ 2026-03-24 11:48  msjing  阅读(0)  评论(0)    收藏  举报