【codevs1227】 方格取数 2
http://codevs.cn/problem/1227/ (题目链接)
题意
N*N的方格,每个格子中有一个数,寻找从(1,1)走到(N,N)的K条路径,使得取到的数的和最大。
Solution
经典的费用流应用吧。
额外添加源点S和汇点T,分别与(1,1)和(N,N)连边。把棋盘中每个点拆成两个,连两条弧。其中一条容量为1,费用为该点的数字大小;另一条容量为inf,费用为0。这就表示一个点的数只能取一次,然后跑最大费用最大流即可。
细节
数组开小。。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | // codevs1227 #include<algorithm> #include<iostream> #include<cstring> #include<cstdlib> #include<cstdio> #include<cmath> #include<queue> #define LL long long #define inf 2147483640 #define Pi acos(-1.0) #define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout); using namespace std; const int maxn=100010; struct edge { int from,to,next,c,w;}e[maxn<<1]; int head[maxn],dis[maxn],vis[maxn],f[maxn],p[maxn]; int cnt=1,n,m,es,et,K; void link( int u, int v, int c, int w) { e[++cnt]=(edge){u,v,head[u],c,w};head[u]=cnt; e[++cnt]=(edge){v,u,head[v],-c,0};head[v]=cnt; } int SPFA() { queue< int > q; memset (dis,-1, sizeof (dis)); q.push(es);dis[es]=0;f[es]=inf; while (!q.empty()) { int x=q.front();q.pop(); vis[x]=0; for ( int i=head[x];i;i=e[i].next) if (e[i].w && dis[e[i].to]<dis[x]+e[i].c) { dis[e[i].to]=dis[x]+e[i].c; f[e[i].to]=min(f[x],e[i].w); p[e[i].to]=i; if (!vis[e[i].to]) q.push(e[i].to),vis[e[i].to]=1; } } if (dis[et]==-1) return 0; for ( int i=p[et];i;i=p[e[i].from]) e[i].w-=f[et],e[i^1].w+=f[et]; return f[et]*dis[et]; } int EK() { int ans=0; for ( int i=1;i<=K;i++) ans+=SPFA(); return ans; } int main() { scanf ( "%d%d" ,&n,&K); es=n*n+1;et=n*n+2; for ( int i=1;i<=n;i++) for ( int x,y,w,j=1;j<=n;j++) { scanf ( "%d" ,&w); x=(i-1)*n+j;y=x+n*n+2; link(x,y,w,1);link(x,y,0,inf); if (i<n) link(y,x+n,0,inf); if (j<n) link(y,x+1,0,inf); } link(es,1,0,inf);link(n*n+n*n+2,et,0,inf); printf ( "%d" ,EK()); return 0; } |
This passage is made by MashiroSky.
分类:
图论--网络流
, 图论--网络流--费用流
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?