CodeFroces 96D Volleyball (最短路预处理跑最短路)

题目大意:给出n个路口,m条路,m条路是无向的,长度为w。然后每个路口都有一个出租车司机,只要坐他的车,就必须交c元,他最多可以载你走的长度为t的路。问从x到y的最小花费是多少。

这道题一开始写懵逼了,想直接跑一遍最短路,都测到test31了,然后wa了。后来想了好久发现,有可能一开始到达了a点,然后走到b,c后回到a,此时也是一种情况,虽然回到来的花费肯定是上涨了,但是他有可能能跑的距离变长了。发现这个我就想稍微改改,然后发现不是MLE就是TLE。。。最后想到最简单的方法就是先预处理一下,每个点可以到达的路都给预处理出来,建立一条花费为c的路,再跑一遍最短路即可。

这样复杂度看上去很高,但是由于是用的spfa,spfa跑稀疏图是很好用的,他的复杂度和边的个数有关,这才1000条边,预处理的时候每个点都跑一跑最短路,也就是n^2的复杂度。

代码如下:

#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<utility>
#include<stack>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;
typedef long long ll;
const int maxn = 10005;
const ll INF = 1e18;
int n, m, x, y;
int head[maxn], to[maxn], nx[maxn], ppp = 0;
ll t[maxn];
ll c[maxn];
ll cost[maxn];

typedef pair<int, ll>pii;
vector<pii>edge[maxn];

void add_edge(int u, int v, ll val) {
	to[ppp] = v, nx[ppp] = head[u], cost[ppp] = val, head[u] = ppp++;swap(u, v);
	to[ppp] = v, nx[ppp] = head[u], cost[ppp] = val, head[u] = ppp++;
}

ll dis[maxn];
void spfa(int s) {
	fill(dis, dis + maxn, INF);
	dis[s] = 0;
	queue <int> q;
	q.push(s);
	while(!q.empty()) {
		int u = q.front();
		q.pop();
		for(int i = head[u]; ~i; i = nx[i]) {
			int v = to[i];
			if(dis[v] > dis[u] + cost[i]) {
				dis[v] = dis[u] + cost[i];
				q.push(v);
			}
		}
	}
}

void spfa2() {
	fill(dis, dis + maxn, INF);
	dis[x] = 0;
	queue <int> q;
	q.push(x);
	while(!q.empty()) {
		int u = q.front();
		q.pop();
		for(int i = 0; i < edge[u].size(); i++) {
			int v = edge[u][i].first;
			if(dis[v] > dis[u] + edge[u][i].second) {
				dis[v] = dis[u] + edge[u][i].second;
				q.push(v);
			}
		}
	}
}

int main() {
#ifndef ONLINE_JUDGE
	freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
#endif
	memset(head, -1, sizeof(head));
	ppp = 0;
	cin >> n >> m;
	cin >> x >> y;
	while(m--) {
		int u, v;
		ll val;
		cin >> u >> v >> val;
		add_edge(u, v, val);
	}
	for(int i = 1; i <= n; i++) {
		cin >> t[i] >> c[i];
	}
	
	for(int i = 1; i <= n; i++) {
		spfa(i);
		for(int j = 1; j <= n; j++) {
			if(i != j && dis[j] <= t[i]) {
				edge[i].push_back(pii(j, c[i]));
			}
		}
	}
	
	spfa2();
	
	if(dis[y] == INF)
		cout << -1 << '\n';
	else
		cout << dis[y] << '\n';
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值