题目链接:BZOJ 2324
对于限制“对于k节点,只有1到k - 1节点都被摧毁时,才能经过节点k”,我们可以通过用floyd处理,设dis[i][j]为i到j经过小于j节点的最短路径,进行转移即可。对于限制“每个节点都要被摧毁”,可以用有下界费用流解决。每个节点拆点,S节点与0节点的流出点连容量为k费用为0的边以保证有k个人到达N号节点。我开始wa了两次,因为我拆点的时候,直接是将点号加上N,但是由于这道题有一个0号节点,所以0节点的出点与N节点的入点重复了QAQ。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
const int inf = (int)1e8;
int N, M, K, S, T;
bool vis[1000];
int head[1000], dep[1000], fa[1000], dis[200][200];
struct node{
int u, v, w, c, next;
}e[200000];
inline int read(){
int x = 0, f = 1; char ch = getchar();
while(ch < '0' || ch > '9'){if(ch == '-')f = -1; ch = getchar();}
while(ch >= '0' && ch <= '9'){x = x * 10 + ch - '0'; ch = getchar();}
return x * f;
}
int k = 0;
void adde(int u, int v, int c, int w){
e[k].u = u; e[k].v = v; e[k].w = w; e[k].c = c; e[k].next = head[u]; head[u] = k++;
e[k].u = v; e[k].v = u; e[k].w =-w; e[k].c = 0; e[k].next = head[v]; head[v] = k++;
}
void input(){
N = read(); M = read(); K = read();
for(int i = 0; i <= N; ++i){
for(int j = 0; j <= N; ++j){
if(i != j)dis[i][j] = inf;
}
}
for(int i = 1; i <= M; ++i){
int x = read(), y = read(), z = read();
dis[x][y] = min(dis[x][y], z); dis[y][x] = dis[x][y];
}
}
void floyd(){
for(int k = 0; k <= N; ++k){
for(int i = 0; i <= N; ++i){
for(int j = 0; j <= N; ++j){
if(k <= i || k <= j){
dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j]);
}
}
}
}
}
queue<int>q;
void work(){
int ans = 0;
while(1){
int Flow = inf;
for(int i = 0; i <= T; ++i)dep[i] = inf;
dep[S] = 0; vis[S] = 1; q.push(S);
while(!q.empty()){
int u = q.front(); q.pop();
for(int i = head[u]; i != -1; i = e[i].next){
int v = e[i].v;
if(dep[u] + e[i].w < dep[v] && e[i].c > 0){
dep[v] = dep[u] + e[i].w; fa[v] = i;
Flow = min(Flow, e[i].c);
if(!vis[v]){
q.push(v); vis[v];
}
}
}
vis[u] = 0;
}
if(dep[T] == inf)break;
ans += dep[T] * Flow;
int t = T;
while(t != S){
e[fa[t]].c -= Flow;
e[fa[t] ^ 1].c += Flow;
t = e[fa[t]].u;
}
}
printf("%d\n", ans);
}
void solve(){
floyd();
memset(head, -1, sizeof(head));
S = N * 2 + 2; T = N * 2 + 3;
for(int i = 1; i <= N; ++i){
adde(S, i + N + 1, 1, 0);
adde(i, T, 1, 0);
adde(i, i + N + 1, 0, 0);
}
adde(S, N + 1, K, 0);
for(int i = 0; i <= N; ++i){
for(int j = i + 1; j <= N; ++j){
if(dis[i][j] != inf){
adde(i + N + 1, j, 1, dis[i][j]);
}
}
}
work();
}
int main(){
input();
solve();
return 0;
}