题意:给你n个城市,m条道路,经过每一条要花费这条路的代价,现给你k个机会,使得最多k条路的代价为0,问从起点s到终点t花费的最少代价
思路:分层图最短路经典裸题
方法一
Code
#include <bits/stdc++.h> using namespace std; struct edge { int to, cost; }; typedef pair<int, int> P; // first是最短距离,second是顶点的编号 const int MAX_V = 2000005; int n, m, s, t, k; int d[MAX_V]; vector<edge> G[MAX_V]; void dijkstra() { priority_queue<P, vector<P>, greater<P> >que; memset(d, 0x3f, sizeof(d)); d[s] = 0; que.push(P(0, s)); while (!que.empty()) { P p = que.top(); que.pop(); int v = p.second; if (d[v] < p.first) continue; for (int i = 0; i < G[v].size(); i++) { edge e = G[v][i]; if (d[e.to] > d[v] + e.cost) { d[e.to] = d[v] + e.cost; que.push(P(d[e.to], e.to)); } } } } int main() { scanf("%d%d%d%d%d", &n, &m, &s, &t, &k); for(int i = 1; i <= m; i++) { int u, v, cost; scanf("%d%d%d", &u, &v, &cost); for(int j = 0; j <= k; j++) { G[u+n*j].push_back({v+n*j,cost}); G[v+n*j].push_back({u+n*j,cost}); if(j < k) { G[u+n*j].push_back({v+n*(j+1),0}); G[v+n*j].push_back({u+n*(j+1),0}); } } } dijkstra(); //int ans=0x3f3f3f3f; //for(int i=0;i<=k;i++) ans=min(ans,dis[t+n*i]); printf("%d ", d[t+k*n]); return 0; }
方法二
让我最惊讶的是这题有的人的Dijkstra算法没经过堆优化直接用暴力出来???后来一看n,m都小于1e3,复杂度最多也就1e6,还爆不了,好吧。当然也有用优化过的算法或者是SPFA,明天再过来看一下
刚才试了一下,不用优先队列优化时间是52ms,优化后是150ms,后来问学长,跟我讲可能由于在点比较少的情况下,排序需要的时间比遍历要多一些
Code
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> P; const int MAX_N=1005; int n, m, s, t, k; vector<P> G[MAX_N]; int d[MAX_N][MAX_N]; void dijkstra() { memset(d, 0x3f, sizeof(d)); d[s][0] = 0; priority_queue<P, vector<P>, greater<P> >que; queue<P> que; que.push({0,s}); while (!que.empty()) { P p = que.front(); que.pop(); int u = p.second%n, t = p.second/n; if (d[u][t]<p.first) continue; for (int i = 0; i < G[u].size(); i++) { int v = G[u][i].first, cost = G[u][i].second; if(d[v][t]>d[u][t]+cost) d[v][t] = d[u][t]+cost, que.push({d[v][t],t*n+v}); if(t<k&&d[v][t+1]>d[u][t]) d[v][t+1] = d[u][t], que.push({d[v][t+1],(t+1)*n+v}); } } } int main() { scanf("%d%d%d%d%d", &n, &m, &s, &t, &k); for(int i=0;i<m;i++) { int u, v, cost; scanf("%d%d%d", &u, &v, &cost); G[u].push_back({v,cost}); G[v].push_back({u,cost}); } dijkstra(); printf("%d ",d[t][k]); return 0; }