生活随笔
收集整理的這篇文章主要介紹了
【P2774】方格取数问题(贪心+最大流,洛谷)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先,我們要讀懂這道題,否則你會和我一開始產生一樣的疑問,把所有的數都取走剩下一個最小的不就可以了么???然后我們發現樣例完全不是這么回事。題目中所說的使相鄰的兩個數沒有公共邊,是指你去走的數,也就是取完之后矩陣里的空白格子。明白了這一點,我們可能會有一個比較基礎的貪心思想,沒錯,就是隔一個取一個,但是這么做并不可行,具體反例很容易找。然后我們通過觀察,發現這道題和某最大權閉合子圖有些類似,如果我們全取所有點,刪去最小割說不準可行。
開始考慮建圖,首先所有的奇數格子連源點,偶數格子連匯點,邊權為點權。他們之間的邊只連奇數到偶數的,邊權為inf,這么連是為了避免重復計算。然后直接DINIC最大流就可以了。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#define ll long long
#define inf 50000000
#define re register
#define id m*(i-1)+j
using namespace std;
struct po
{int from,to,dis,nxt;
}edge[1000001];
int head[
1000001],cur[
1000001],dep[
60001],n,m,s,t,u,num=-
1,x,y,l,tot,sum,d;
int nm,a[
120][
120];
int dx[
5]={
0,
1,
0,-
1,
0};
int dy[
5]={
0,
0,
1,
0,-
1};
inline int read()
{int x=
0,c=
1;char ch=
' ';while((ch>
'9'||ch<
'0')&&ch!=
'-')ch=
getchar();while(ch==
'-')c*=-
1,ch=
getchar();while(ch<=
'9'&&ch>=
'0')x=x*
10+ch-
'0',ch=
getchar();return x*
c;
}
inline void add_edge(
int from,
int to,
int dis)
{edge[++num].nxt=head[
from];edge[num].from=
from;edge[num].to=
to;edge[num].dis=
dis;head[from]=
num;
}
inline void add(
int from,
int to,
int dis)
{add_edge(from,to,dis);add_edge(to,from,
0);
}
inline bool bfs()
{memset(dep,0,
sizeof(dep));queue<
int>
q;while(!
q.empty())q.pop();dep[s]=
1;q.push(s);while(!
q.empty()){int now=
q.front();q.pop();for(re
int i=head[now];i!=-
1;i=
edge[i].nxt){int v=
edge[i].to;if(dep[v]==
0&&edge[i].dis>
0){dep[v]=dep[now]+
1;if(v==
t)return 1;q.push(v); }}}return 0;
}
inline int dfs(
int u,
int dis)
{if(u==
t)return dis;int diss=
0;for(re
int i=head[u];i!=-
1;i=
edge[i].nxt){int v=
edge[i].to;if(dep[v]==dep[u]+
1&&edge[i].dis!=
0){int check=
dfs(v,min(dis,edge[i].dis));if(check>
0){diss+=
check;dis-=
check;edge[i].dis-=
check;edge[i^
1].dis+=
check;if(dis==
0)
break;}}}return diss;
}
inline int dinic()
{int ans=
0;while(bfs()){for(re
int i=
0;i<=t;i++
)cur[i]=
head[i];while(
int d=
dfs(s,inf))ans+=
d;}return ans;
}
int main()
{memset(head,-
1,
sizeof(head));n=read();m=
read();s=
0;t=n*m+
1;for(re
int i=
1;i<=n;i++
)for(re
int j=
1;j<=m;j++
)a[i][j]=read(),sum+=
a[i][j];for(re
int i=
1;i<=n;i++
)for(re
int j=
1;j<=m;j++
){if((i+j)%
2==
0)add(s,id,a[i][j]);elseadd(id,t,a[i][j]);for(re
int h=
1;h<=
4;h++
){int lx=i+dx[h],ly=j+
dy[h];if(lx>=
1&&lx<=n&&ly>=
1&&ly<=
m)if((lx+ly)%
2!=
0)add(id,(lx-
1)*m+
ly,inf);}}cout<<sum-
dinic();
} ?
轉載于:https://www.cnblogs.com/victorique/p/8426683.html
總結
以上是生活随笔為你收集整理的【P2774】方格取数问题(贪心+最大流,洛谷)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。