Codeforces 96D Volleyball spfa

本文深入探讨了使用SPFA算法解决图论问题的方法,通过实例展示了如何在给定无向图中找到从起点到终点的最小费用路径。文章详细介绍了算法的实现过程、关键步骤和优化技巧,旨在帮助读者理解和掌握该算法在实际问题中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:点击打开链接

题意:

给定n个点m条边的无向图

起点、终点

下面m行表示边和边权

再下面n行表示每个点有一辆出租车,这辆出租车能开的最远距离和搭乘这辆车的费用

问到终点的最小费用

开始感觉复杂度太大不好下手,暴力出奇迹。。

Y一下即可得到 spfa套spfa

注意inf要足够大,__int64


#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<set>
#include<queue>
#include<map>
#include<vector>
using namespace std;
#define N 1005
#define inf 10000000000000
#define ll __int64
struct Edge{
	ll from, to, dis, nex;
}edge[N<<1];
ll head[N],edgenum;
void add(ll u,ll v,ll d){
	Edge E = {u,v,d,head[u]};
	edge[edgenum] = E;
	head[u] = edgenum++;
}
ll cost[N], far[N];
vector<ll>G[N];
ll dis[N];
bool vis[N], inq[N];
ll n, m, st, en;
void dou(ll x){
	if(vis[x])return;
	vis[x] = 1;
	for(ll i = 1; i <= n; i++)dis[i] = inf, inq[i] = 0;
	dis[x] = 0;
	queue<ll>q; q.push(x);
	while(!q.empty()){
		ll u = q.front(); q.pop(); inq[u] = 0;
		for(ll i = head[u]; ~i; i = edge[i].nex){
			ll v = edge[i].to;
			if(dis[u]+edge[i].dis<=far[x] && dis[v]>dis[u]+edge[i].dis){
				dis[v] = edge[i].dis+dis[u];
				if(!inq[v])inq[v] = 1, q.push(v);
			}
		}
	}
	for(ll i = 1; i <= n; i++)if(!vis[i] && dis[i]<=far[x])G[x].push_back(i);
}
ll ned[N];
bool hehe[N];
ll bfs(){
	for(ll i = 1; i <= n; i++)ned[i] = inf, hehe[i] = 0;
	ned[st] = 0;
	queue<ll>q;
	q.push(st);
	hehe[en] = 1;
	while(!q.empty()){
		ll u = q.front(); q.pop(); hehe[u] = 0;
		dou(u);
		for(ll i = 0; i < G[u].size(); i++){
			ll v = G[u][i];
			if(ned[v]>ned[u]+cost[u]){
				ned[v] = ned[u]+cost[u];
				if(!hehe[v])hehe[v]=1,q.push(v);
			}
		}
	}
	if(ned[en]==inf)return -1;
	return ned[en];
}
void init(){
	memset(vis, 0, sizeof vis);
	for(ll i = 1; i <= n; i++)G[i].clear();
	memset(head,-1,sizeof head); edgenum = 0;
}
int main(){
	ll i, j, u, v, d;
	while(cin>>n>>m){
		init();
		cin>>st>>en;
		while(m--){
			cin>>u>>v>>d;
			add(u,v,d);
			add(v,u,d);
		}
		for(i=1;i<=n;i++)cin>>far[i]>>cost[i];
		cout<<bfs()<<endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值