建图:建立源点 s 和汇点 t,对于方格上的每个点来说其上的值只能取一次,即对点有限制,需要拆点,即将方格上的每个点拆分为入点和出点,入点向出点连边,容量为 1,费用为点权,又由于一个点可以经过多次,即可能存在这样一种情况:再次经过该点,但没有权值,不妨再次从入点向出点连边,容量足够大,费用为 0,同时原方格中点与点之间也需要连边,即每个点的出点需要向其下方和右方的点的入点连边,容量足够大,费用为 0,另外,源点向方格左上角的第一个点的入点连边,容量为 k,费用为 0,方格右下角的最后一个点的出点向 t 连边,容量为 k,费用为 0,最后求解从 s 到 t 的最大费用最大流即为所求 为什么?
不难发现,建立的流网络中的可行流与实际问题是一一对应的,即从 s 出发最多 k 的流量,另外到 t 也最多 k 的流量,对应 k 条不同的路径,对应流网络中的每一条 1 单位的流量对应一条路径,对于某条入点连向出点的边来说,由于其容量为 1,即一条路径只会经过该边一次,即取其权值一次,其他经过该点只能通过另外一条没有费用的边,即可能多次经过该点
时间复杂度:O(n4k)
代码
// Problem: K取方格数// Contest: AcWing// URL: https://www.acwing.com/problem/content/384/// Memory Limit: 64 MB// Time Limit: 1000 ms// // Powered by CP Editor (https://cpeditor.org)// %%%Skyqwq#include<bits/stdc++.h>//#define int long long#define help {cin.tie(NULL); cout.tie(NULL);}#define pb push_back#define fi first#define se second#define mkp make_pairusingnamespace std;
typedeflonglong LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
template <typename T> boolchkMax(T &x, T y){ return (y > x) ? x = y, 1 : 0; }
template <typename T> boolchkMin(T &x, T y){ return (y < x) ? x = y, 1 : 0; }
template <typename T> voidinlineread(T &x){
int f = 1; x = 0; char s = getchar();
while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
x *= f;
}
constint N=5005,M=(N*2+N*2)*2,inf=1e9;
int n,k,S,T;
int h[N],f[M],w[M],ne[M],e[M],idx;
int d[N],pre[N],incf[N],q[N];
bool st[N];
voidadd(int a,int b,int c,int d){
e[idx]=b,f[idx]=c,w[idx]=d,ne[idx]=h[a],h[a]=idx++;
e[idx]=a,f[idx]=0,w[idx]=-d,ne[idx]=h[b],h[b]=idx++;
}
intget(int x,int y,int t){
return (x*n+y)*2+t;
}
boolspfa(){
memset(d,-0x3f,sizeof d);
memset(incf,0,sizeof incf);
d[S]=0,incf[S]=inf,q[0]=S;
int hh=0,tt=1;
while(hh!=tt)
{
int x=q[hh++];
if(hh==N)hh=0;
st[x]=false;
for(int i=h[x];~i;i=ne[i])
{
int y=e[i];
if(d[y]<d[x]+w[i]&&f[i])
{
d[y]=d[x]+w[i];
pre[y]=i;
incf[y]=min(incf[x],f[i]);
if(!st[y])
{
q[tt++]=y;
if(tt==N)tt=0;
st[y]=true;
}
}
}
}
return incf[T]>0;
}
intEK(){
int cost=0;
while(spfa())
{
int t=incf[T];
cost+=t*d[T];
for(int i=T;i!=S;i=e[pre[i]^1])f[pre[i]]-=t,f[pre[i]^1]+=t;
}
return cost;
}
intmain(){
memset(h,-1,sizeof h);
scanf("%d%d",&n,&k);
S=n*n*2,T=S+1;
add(S,get(0,0,0),k,0);
add(get(n-1,n-1,1),T,k,0);
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
int c;
scanf("%d",&c);
add(get(i,j,0),get(i,j,1),1,c);
add(get(i,j,0),get(i,j,1),inf,0);
if(i+1<n)
add(get(i,j,1),get(i+1,j,0),inf,0);
if(j+1<n)
add(get(i,j,1),get(i,j+1,0),inf,0);
}
printf("%d",EK());
return0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!