题目链接:
https://ac.nowcoder.com/acm/contest/884/J
题意:
给一个无向图,求从起点S到达终点T最多可以消除K条边的最小路径长度。
题解:
解①:
这显然是一个DP题,设f[i][j]f[i][j]f[i][j]为从S到达iii点消除jjj条边的最小路径长度,
状态转移方程为:f[to][j]=min(f[to][j],min(f[from][j]+dis[from][to],f[from][j−1]))f[to][j] = min(f[to][j], min(f[from][j] + dis[from][to], f[from][j-1]))f[to][j]=min(f[to][j],min(f[from][j]+dis[from][to],f[from][j−1]))
边跑最短路边DP即可
解②:
这里还有种做法是直接跑最短路,然后将去掉最短路径上的K条路,剩下的路径求和即为答案。这个一开始想过,还以为是错的就想用DP来做,没有证明过。
代码:
解法1:
const int MAX = 1e3 + 10;
int N, M, S, T, K;
int dis[MAX][MAX];
struct edge {
int nxt, to, w;
}e[MAX * 2];
int head[MAX], tot;
void add(int u, int v, int w) {
e[++tot].nxt = head[u];
e[tot].to = v;
e[tot].w = w;
head[u] = tot;
}
struct node {
int u, d, k;
bool operator <(const node& rhs) const {
if (d == rhs.d)return k > rhs.k;
return d > rhs.d;
}
};
priority_queue<node> q;
void dijkstra(int s) {
memset(dis, 0x3f, sz(dis));
dis[s][0] = 0;
q.push(node{ s,0,0 });
while (!q.empty()) {
node u = q.top(); q.pop();
int k = u.k, now = u.u;
for (int i = head[now]; i; i = e[i].nxt) {
int to = e[i].to, w = e[i].w;
if (dis[now][k] + w < dis[to][k])
dis[to][k] = dis[now][k] + w, q.push(node{ to, dis[to][k], k });
if (k + 1 <= K && dis[now][k] < dis[to][k + 1])
dis[to][k + 1] = dis[now][k], q.push(node{ to, dis[to][k + 1], k + 1 });
}
}
}
int main() {
tot = 0;
scanf("%d%d%d%d%d", &N, &M, &S, &T, &K);
for (int i = 1; i <= M; i++) {
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
if (u == v)continue;
add(u, v, w);
add(v, u, w);
}
dijkstra(S);
int ans = INF;
for (int i = 0; i <= K; i++)ans = min(ans, dis[T][i]);
printf("%d\n", ans);
return 0;
}
解法2:
const int MAX = 1e3 + 10;
int N, M, S, T, K;
int dis[MAX], vis[MAX], pre[MAX], cost[MAX];
struct edge {
int nxt, to, w;
}e[MAX * 2];
int head[MAX], tot;
void add(int u, int v, int w) {
e[++tot].nxt = head[u];
e[tot].to = v;
e[tot].w = w;
head[u] = tot;
}
struct node {
int u, d;
bool operator <(const node& rhs) const {
return d > rhs.d;
}
};
priority_queue<node> q;
void dijkstra(int s) {
memset(dis, 0x3f, sz(dis));
dis[s] = 0;
q.push(node{ s,0 });
while (!q.empty()) {
node u = q.top(); q.pop();
int now = u.u;
if (vis[now])continue;
vis[now] = 1;
for (int i = head[now]; i; i = e[i].nxt)
if (dis[now] + e[i].w < dis[e[i].to]) {
dis[e[i].to] = dis[now] + e[i].w;
pre[e[i].to] = now;
cost[e[i].to] = e[i].w;
if (!vis[e[i].to])
q.push(node{ e[i].to, dis[e[i].to] });
}
}
}
priority_queue<int, vector<int>, greater<int> > qq;
int main() {
tot = 0;
scanf("%d%d%d%d%d", &N, &M, &S, &T, &K);
for (int i = 1; i <= M; i++) {
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
if (u == v)continue;
add(u, v, w);
add(v, u, w);
}
dijkstra(S);
for (int i = T; i != S; i = pre[i])qq.push(cost[i]);
int cnt = max(0, (int)qq.size() - K), ans = 0;
while (cnt--) {
ans += qq.top(); qq.pop();
}
printf("%d\n", ans);
return 0;
}