分层图,k只有10,每个k一层图
跑费用流,但容量为1,所以就是SPFA
# include <bits/stdc++.h>
# define RG register
# define IL inline
# define ID(a, b, c) ((c) * N * N + (a - 1) * N + b)
# define Fill(a, b) memset(a, b, sizeof(a))
# define Copy(a, b) memcpy(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(2e5 + 10), __(3e7 + 10), INF(2e9);
IL ll Read(){
char c = '%'; ll x = 0, z = 1;
for(; c > '9' || c < '0'; c = getchar()) if(c == '-') z = -1;
for(; c >= '0' && c <= '9'; c = getchar()) x = x * 10 + c - '0';
return x * z;
}
int N, K, A, B, C;
int cnt, fst[_], w[__], to[__], nxt[__], dis[_], vis[_], S, T, cost[__], pe[_], pv[_], max_flow, min_cost;
queue <int> Q;
IL void Add(RG int u, RG int v, RG int f, RG int co){
cost[cnt] = co; w[cnt] = f; to[cnt] = v; nxt[cnt] = fst[u]; fst[u] = cnt++;
cost[cnt] = -co; w[cnt] = 0; to[cnt] = u; nxt[cnt] = fst[v]; fst[v] = cnt++;
}
IL bool Bfs(){
Q.push(S); Fill(dis, 127); dis[S] = 0; vis[S] = 1;
while(!Q.empty()){
RG int u = Q.front(); Q.pop();
for(RG int e = fst[u]; e != -1; e = nxt[e]){
if(!w[e] || dis[to[e]] <= dis[u] + cost[e]) continue;
dis[to[e]] = dis[u] + cost[e];
pe[to[e]] = e; pv[to[e]] = u;
if(!vis[to[e]]) vis[to[e]] = 1, Q.push(to[e]);
}
vis[u] = 0;
}
if(dis[T] >= dis[T + 1]) return 0;
RG int ret = INF;
for(RG int u = T; u != S; u = pv[u]) ret = min(ret, w[pe[u]]);
for(RG int u = T; u != S; u = pv[u]) w[pe[u]] -= ret, w[pe[u] ^ 1] += ret;
min_cost += ret * dis[T]; max_flow += ret;
return 1;
}
int main(RG int argc, RG char *argv[]){
Fill(fst, -1);
N = Read(); K = Read(); A = Read(); B = Read(); C = Read();
for(RG int i = 1; i <= N; ++i)
for(RG int j = 1; j <= N; ++j){
RG int gg = Read();
if(gg){
for(RG int k = 0; k < K; ++k){
if(i < N) Add(ID(i, j, k), ID(i + 1, j, K - 1), 1, A);
if(j < N) Add(ID(i, j, k), ID(i, j + 1, K - 1), 1, A);
if(i > 1) Add(ID(i, j, k), ID(i - 1, j, K - 1), 1, A + B);
if(j > 1) Add(ID(i, j, k), ID(i, j - 1, K - 1), 1, A + B);
}
}
else{
for(RG int k = 0; k < K; ++k) Add(ID(i, j, k), ID(i, j, K), 1, A + C);
for(RG int k = 1; k <= K; ++k){
if(i < N) Add(ID(i, j, k), ID(i + 1, j, k - 1), 1, 0);
if(j < N) Add(ID(i, j, k), ID(i, j + 1, k - 1), 1, 0);
if(i > 1) Add(ID(i, j, k), ID(i - 1, j, k - 1), 1, B);
if(j > 1) Add(ID(i, j, k), ID(i, j - 1, k - 1), 1, B);
}
}
}
T = N * N * (K + 1) + 1; Add(S, ID(1, 1, K), 1, 0);
for(RG int i = 0; i <= K; ++i) Add(ID(N, N, i), T, 1, 0);
while(Bfs()); printf("%d
", min_cost);
return 0;
}