[最小割] Topcoder SRM558Div1. SurroundingGame

对网格黑白染色

黑的格子和源点连边,白的格子和汇点连边

因为如果保留benefit就必去删去cost或者所以和他相连的格子的cost

[最小割] Topcoder SRM558Div1. SurroundingGame_第1张图片

大概是这样
跑最小割

#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

const int N=100010,U=200,inf=1e9;

int n,m,S,T,cnt=1,cur[N],G[N],c[25][25],b[25][25],g[25][25];
struct edge{
  int t,nx,f;
}E[N<<1];

inline void addedge(int x,int y,int f){
  E[++cnt].t=y; E[cnt].nx=G[x]; E[cnt].f=f; G[x]=cnt;
  E[++cnt].t=x; E[cnt].nx=G[y]; E[cnt].f=0; G[y]=cnt;
}

int dis[N];
queue<int> Q;

inline bool bfs(){
  while(!Q.empty()) Q.pop();
  for(int i=0;i<=T;i++) dis[i]=-1;
  dis[S]=0; Q.push(S);
  while(!Q.empty()){
    int x=Q.front(); Q.pop();
    for(int i=G[x];i;i=E[i].nx)
      if(E[i].f && !~dis[E[i].t]){
    dis[E[i].t]=dis[x]+1;
    if(E[i].t==T) return true;
    Q.push(E[i].t);
      }
  }
  return false;
}

int dfs(int x,int f){
  if(x==T || !f) return f;
  int used=0,w;
  for(int &i=cur[x];i;i=E[i].nx)
    if(E[i].f && dis[E[i].t]==dis[x]+1){
      w=dfs(E[i].t,min(f-used,E[i].f));
      E[i].f-=w; E[i^1].f+=w;
      if((used+=w)==f) return used;
    }
  if(!used) dis[x]=-1;
  return used;
}

inline int cst(char x){
  if(x>='0' && x<='9') return x-'0';
  if(x>='a' && x<='z') return x-'a'+10;
  return x-'A'+36;
}

class SurroundingGame{
public:
  int maxScore(vector<string> cost,vector<string> benefit){
    n=cost.size(); m=cost[0].size();
    int ans=0;
    for(int i=1;i<=n;i++)
      for(int j=1;j<=m;j++){
    c[i][j]=cst(cost[i-1][j-1]);
    b[i][j]=cst(benefit[i-1][j-1]);
    g[i][j]=T++;
    ans+=b[i][j];
      }
    S=T*2; T=S+1;
    for(int i=1;i<=n;i++)
      for(int j=1;j<=m;j++)
    if((i+j)&1){
      addedge(S,g[i][j]*2,c[i][j]);
      addedge(g[i][j]*2,g[i][j]*2+1,b[i][j]);
      if(i+1<=n) addedge(g[i][j]*2+1,g[i+1][j]*2,inf);
      if(i-1>0) addedge(g[i][j]*2+1,g[i-1][j]*2,inf);
      if(j+1<=m) addedge(g[i][j]*2+1,g[i][j+1]*2,inf);
      if(j-1>0) addedge(g[i][j]*2+1,g[i][j-1]*2,inf);
    }
    else{
      addedge(g[i][j]*2+1,g[i][j]*2,b[i][j]);
      addedge(g[i][j]*2,T,c[i][j]);
      if(i+1<=n) addedge(g[i+1][j]*2,g[i][j]*2+1,inf);
      if(i-1>0) addedge(g[i-1][j]*2,g[i][j]*2+1,inf);
      if(j+1<=m) addedge(g[i][j+1]*2,g[i][j]*2+1,inf);
      if(j-1>0) addedge(g[i][j-1]*2,g[i][j]*2+1,inf);
    }
    while(bfs()){
      for(int i=0;i<=T;i++) cur[i]=G[i];
      ans-=dfs(S,inf);
    }
    return ans;
  }
}Main;

int main(){
  vector<string> a={"asam",
            "atik"};
  vector<string> b={"123A",
            "45BC"};
  cout<for(;;);
}

你可能感兴趣的:(网络流,Thinking,Training)