跳到正文

算法·理论

单元最短路模板

_pzy约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年1月21日
收录
2025年12月12日
更新
2026年11月9日
篇幅
约 5 分钟
获赞
1

版本

  1. v1当前

代码

dijkstra

C++
#include<bits/stdc++.h>
using namespace std;
int n,m,k,head[100005],cnt,dis[100005];
priority_queue< pair<int,int> ,vector< pair<int,int> >,greater< pair<int,int> > > q;
struct abc
{
	int to,size,next;
}a[100005];
void add(int x,int y,int z)
{
	cnt++;
	a[cnt].to=y;
	a[cnt].next=head[x];
	a[cnt].size=z;
	head[x]=cnt;
	return ;
}
void dijkstra(int x)
{
	int f[100005];
	memset(dis,0x3f,sizeof(dis));
	memset(f,0,sizeof(f));
	dis[x]=0;
	q.push({0,x});
	while(!q.empty())
	{
		pair<int,int> t=q.top();
		q.pop();
		if(f[t.second]==1)
		{
			continue;
		}
		f[t.second]=1;
		for(int i=head[t.second];;i=a[i].next)
		{
			if(i==0)
			{
				break;
			}
			if(dis[a[i].to]>t.first+a[i].size)
			{
				dis[a[i].to]=t.first+a[i].size;
				q.push({dis[a[i].to],a[i].to});
			}
		}
	}
	return ;
}
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);
	}
	dijkstra(1);
	if(dis[k]==0x3f3f3f3f)
	{
		cout<<-1;
	}
	else
	{
		cout<<dis[k];
	}
	return 0;
} 

SPFA

C++
#include<bits/stdc++.h>
using namespace std;
int n,m,st,en,dis[100005];
bool is=true;
vector<pair<int,int> > e[1000005];
void SPFA(int x)
{
    memset(dis,0x3f,sizeof dis);
    queue<int> q;
    q.push(x);
    int ch[1000005],ch2[1000005];
    memset(ch,0,sizeof ch);
    memset(ch2,0,sizeof ch2);
    ch[x]=1;ch2[x]=1;
    dis[x]=0;
    while(!q.empty())
    {
        int now=q.front();
        q.pop();
        ch2[now]=0;
        for(int i=0;i<e[now].size();i++)
        {
            int son=e[now][i].first,w=e[now][i].second;
            if(dis[son]>dis[now]+w)
            {
                dis[son]=dis[now]+w;
                if(ch2[son]==0)
                {
                    ch[son]++;
                    q.push(son);
                    ch2[son]=1;
                    if(ch[son]>=n)
                    {
                        is=false;
                        break;
                    }
                }
            }
        }
        if(!is)
        {
            break;
        }
    }
}
int main()
{
	cin>>n>>m>>st>>en;
    for(int i=1;i<=m;i++)
    {
        int x,y,z;
        cin>>x>>y>>z;
        e[x].push_back({y,z});
    }
    SPFA(st);
    if(!is)
    {
        cout<<"NO";
        return 0;
    }
    cout<<dis[en];
	return 0;
} 

暂有问题。

pAwNWCV.png

原文