路线(acwing)"/>
c++通行路线(acwing)
在郊区有 N 座通信基站,P条 双向 电缆,第 i 条电缆连接基站 Ai 和 Bi。
特别地,1 号基站是通信公司的总站,N 号基站位于一座农场中。
现在,农场主希望对通信线路进行升级,其中升级第 i 条电缆需要花费 Li。
电话公司正在举行优惠活动。
农产主可以指定一条从 1 号基站到 N号基站的路径,并指定路径上不超过 K 条电缆,由电话公司免费提供升级服务。
农场主只需要支付在该路径上剩余的电缆中,升级价格最贵的那条电缆的花费即可。
求至少用多少钱可以完成升级。
输入格式
第 11 行:三个整数 N,P,K。
第 2..P+1行:第 i+1 行包含三个整数 Ai,Bi,Li。
输出格式
包含一个整数表示最少花费。
若 1 号基站与 N 号基站之间不存在路径,则输出 −1。
数据范围
0≤K<N≤1000,
1≤P≤10000,
1≤Li≤1000000
输入样例:
5 7 1
1 2 5
3 1 4
2 4 8
3 2 3
5 2 9
3 4 7
4 5 6
输出样例:
4
代码如下
#include<cstring>
#include<iostream>
#include<algorithm>
#include<deque>using namespace std;typedef pair<int, int> PII;
const int N = 1010, M = 20010, INF = 0x3f3f3f3f;int n, m, k;
int h[N], w[M], e[M], ne[M], idx;
int dist[N];
bool st[N];void add(int a, int b, int c)
{e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}bool check(int bound)
{memset(dist, 0x3f, sizeof dist);memset(st, 0, sizeof st);dist[1] = 0;deque<int> q;q.push_front(1);while(q.size()){auto t = q.front();q.pop_front();if(st[t]) continue;st[t] = true;for(int i = h[t]; ~ i; i = ne[i]){int j = e[i], x = w[i] > bound;if(dist[j] > dist[t] + x){dist[j] = dist[t] + x;if(!x) q.push_front(j);else q.push_back(j);}}}return dist[n] <= k;
}int main()
{cin >> n >> m >> k;memset(h, -1, sizeof h);while(m --){int a, b, c;scanf("%d%d%d",&a, &b, &c);add(a, b, c), add(b, a, c);}int l = 0, r = 1e6 + 1;while(l < r){int mid = l + r >> 1;if(check(mid)) r = mid;else l = mid + 1;}if(r == 1e6 + 1) cout << -1 << endl;else cout << r << endl;return 0;
}
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
typedef pair<int, int> PII;
const int INF = 0x3f3f3f3f;
const int N = 1010, M = 20010, K = 1010;int n, m, k;
int h[N], w[M], e[M], ne[M], idx;
int dist[N][K]; //dist[x][k]表示从1到达x节点,途中使用k次免费升级的最小花费
bool vis[N][K];void add(int a, int b, int c) {e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}int spfa() {memset(dist, 0x3f, sizeof dist);dist[1][0] = 0;queue<PII> q;q.emplace(1, 0);vis[1][0] = true;while (!q.empty()) {auto [v, cnt] = q.front();q.pop();vis[v][cnt] = false;for (int i = h[v]; ~i; i = ne[i]) {int j = e[i];if (cnt < k && dist[j][cnt + 1] > dist[v][cnt]) { //使用一次免费升级dist[j][cnt + 1] = dist[v][cnt];if (!vis[j][cnt + 1]) {q.emplace(j, cnt + 1);vis[j][cnt + 1] = true;}}if (dist[j][cnt] > max(w[i], dist[v][cnt])) { //不使用免费升级dist[j][cnt] = max(w[i], dist[v][cnt]);if (!vis[j][cnt]) {q.emplace(j, cnt);vis[j][cnt] = true;}}}}int res = INF;for (int i = 0; i <= k; i++) {res = min(res, dist[n][i]);}return res == INF ? -1 : res;
}int main() {scanf("%d%d%d", &n, &m, &k);memset(h, -1, sizeof h);while (m--) {int a, b, c;scanf("%d%d%d", &a, &b, &c);add(a, b, c), add(b, a, c);}cout << spfa() << endl;return 0;
}
第二个代码来自AcWing 340. 通信线路 - AcWing
二分:求最小值,使用二分,如果边权大于当前中间值,放入队尾,否则放在对头
分层图:重点在函数的最后几行,再使用了1~k层分层图中,寻找最小的值emplace和push作用一样
更多推荐
c++通行路线(acwing)
发布评论