跳到正文

个人记录

图论板子

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

文章信息

发布
2025年7月2日
收录
2025年12月12日
更新
2026年11月8日
篇幅
约 5 分钟

版本

  1. v1当前

dij

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int kN=1e5+7;
int n,m,s;
struct node{
	int x,w;
	bool operator<(const node &b)const
	{
		return b.w<w;
	}
};
vector<node>g[kN];
priority_queue<node>p;
int a[kN];
bool vis[kN];
void dij(){
	for(int i=1;i<=n;++i){
		vis[i]=0;
		a[i]=1e18;
	}
	a[s]=0;
	p.push({s,0});
	while(!p.empty()){
		node t=p.top();
		p.pop();
		int u=t.x;
		if(vis[u]){
			continue;
		}
		vis[u]=1;
		for(int i=0;i<g[u].size();++i){
			int x=g[u][i].x;
			int w=g[u][i].w;
			if(a[x]>a[u]+w){
				a[x]=a[u]+w;
				if(!vis[x]){
					p.push({x,a[x]});
				}
			}
		} 	
	}
	return ;
}
signed main(){
	cin>>n>>m>>s;
	for(int i=1;i<=m;++i){
		int x,y,z;
		cin>>x>>y>>z;
		g[x].push_back({y,z});
	}
	dij();
	for(int i=1;i<=n;++i){
		cout<<a[i]<<" ";
	}
	return 0;
}

floyd

C++
#include<bits/stdc++.h>
using namespace std;
const int kN=1e3+7;
int n,m;
int k;
int dp[kN][kN];
signed main()
{
	cin>>n>>k;
	m=n;
	for(int i=1;i<=n;++i)
	{
		for(int j=1;j<=m;++j)
		{
			if(i!=j)
			dp[i][j]=1e9;
		}
	}
	while(k--)
	{
		int x,y,z;
		cin>>x>>y>>z;
    dp[y][x]=min(z,dp[x][y]);
		dp[x][y]=min(z,dp[y][x]);
	}
	for(int k=1;k<=n;++k)
	{
		for(int i=1;i<=n;++i)
		{
			for(int j=1;j<=n;++j)
			{
				dp[i][j]=min(dp[i][j],
				dp[i][k]+dp[k][j]);
			}
		}
	}
	for(int i=1;i<=n;++i)
	{
		for(int j=1;j<=m;++j)
		{
			cout<<dp[i][j]<<" ";
		}
		cout<<"\n";
	}
	return 0;
}

ballman

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
int n,k,dis[100005];
struct node{
	int u,v;
}e[100005];
signed main(){
	
    ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>k;
	dis[1]=1;
	for(int i=2;i<=n;i++)dis[i]=1e18;
	for(int i=1;i<=n;i++){
		cin>>e[i].u>>e[i].v;
	}
	while(1){
		bool flag=0;
		for(int i=1;i<=n;i++){
			int u=e[i].u,v=e[i].v;
			if(dis[v]>dis[u]+1){
				flag=1;
				dis[v]=dis[u]+1;
			}
		}
		if(!flag)break;
	}
	if(dis[k]==1e18){
		cout<<-1;
		return 0;
	}
	cout<<dis[k];
	return 0;
}

spfa

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int kN=1e5+7;
int n,m,s;
struct node{
	int x,w;
};
vector<node>g[kN];
queue<int>p;
int a[kN];
bool vis[kN];
void spfa(){
	for(int i=1;i<=n;++i){
		vis[i]=0;
		a[i]=1e18;
	}
	a[s]=0;
	p.push(s);
	while(!p.empty()){
		int u=p.front();
		p.pop();
		for(int i=0;i<g[u].size();++i){
			int x=g[u][i].x;
			int w=g[u][i].w;
			if(a[x]>a[u]+w){
				a[x]=a[u]+w;
				if(!vis[x]){
					p.push(x);
				}
			}
		} 	
	}
	return ;
}
signed main(){
	cin>>n>>m;s=1;
	for(int i=1;i<=m;++i){
		int x,y,z;
		cin>>x>>y>>z;
		g[x].push_back({y,z});
		g[y].push_back({x,z});
	}
	spfa();
	cout<<a[n];
	return 0;
}
原文