A businessman walks through a n*n square grid to attend a very important business event. He's going to go from the top left corner of the grid and out the bottom right corner. It takes 1 units of time to cross 1 squares in the middle of each one. The businessman must cross out at (2n-1) a unit time. And in the middle of every small box, you need to pay a certain fee.
The businessman expected to cross out at a minimum cost within the stipulated time. How much do I need at least?
Note: You cannot cross the small squares diagonally (that is, you can only move up and down in four directions and not leave the grid).
#include <cstdio>#include<queue>#defineM 100000#defineN 105#defineINF 0x3f3f3f3fusing namespacestd;BOOLInq[n];intN,s,t,cnt=1, fx[5]= {1,-1,0,0},fy[5]= {0,0,-1,1},a[n][n],to[m<<1],dis[m],fa[m],head[m],came[m<<1],nxt[m<<1],flow[m<<1],cost[m<<1];voidInsintUintVintWintf) {nxt[++cnt]=head[u];to[cnt]=v;flow[cnt]=w;cost[cnt]=f;head[u]=CNT; nxt[++cnt]=head[v];to[cnt]=u;flow[cnt]=0; cost[cnt]=-f;head[v]=CNT;}BOOLSPFA () { for(intI=s; i<=t; ++i) dis[i]=inf,inq[i]=false, came[i]=inf; Queue<int>Q; Dis[s]=0; Q.push (S); for(intu;!Q.empty ();) {u=Q.front (); Q.pop (); Inq[u]=false; for(intI=head[u]; I I=Nxt[i]) { intv=To[i]; if(dis[v]>dis[u]+cost[i]&&Flow[i]) {Dis[v]=dis[u]+Cost[i]; FA[V]=i; CAME[V]=min (came[u],flow[i]); if(!Inq[v]) {Inq[v]=true; Q.push (v); } } } } returndis[t]<inf;}intMainintargcChar*argv[]) {scanf ("%d",&N); S=0; T=n*n*2+1; for(intI=1; i<=n; ++i) for(intj=1; j<=n; ++j) scanf ("%d",&A[i][j]); Ins (S,1, inf,a[1][1]); INS (n*n,t,inf,0); for(intI=1; i<=n; ++i) { for(intj=1; j<=n; ++j) {ins ((I-1) *n+j, (I-1) *n+j+n*n,1,0); for(intk=0; k<4; ++k) {intti=i+fx[k],tj=j+Fy[k]; if(ti<1|| ti>n| | tj<1|| Tj>n)Continue; Ins ((I-1) *n+j+n*n, (ti-1) *N+TJ,1, A[TI][TJ]); } } } intans=0; while(SPFA ()) {intt=Came[t]; for(intl=1; I!=s; i=to[fa[i]^1]) {Flow[fa[i]]-=T; Flow[fa[i]^1]+=T; } ans+=t*Dis[t]; } printf ("%d\n", ans); return 0;}
Dp
#include <iostream>using namespacestd;intn,a[118][118],f[118][118];intMain () {CIN>>N; for(intI=1; i<=n; i++) for(intj=1; j<=n; J + +) {cin>>A[i][j]; if(j==1) F[i][j]=f[i-1][j]+A[i][j]; Else if(i==1) F[i][j]=f[i][j-1]+A[i][j]; ElseF[i][j]=min (f[i-1][j]+a[i][j],f[i][j-1]+A[i][j]); } cout<<F[n][n]; return 0;}