[网络流] Topcoder SRM556DIV. OldBridges

只有一个人的时候,可以把图建出来看是否满流

但是两个人的时候会出现特殊情况

这里写图片描述

把b1和b2反过来在跑一遍就好了

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>

using namespace std;

const int N=10010,inf=1<<29;

int n,cnt,S,T,cur[N],G[N];
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]; G[x]=cnt; E[cnt].f=f;
  E[++cnt].t=x; E[cnt].nx=G[y]; G[y]=cnt; E[cnt].f=0;
}

inline void Pre(vector<string> b){
  cnt=1; T=n+1;
  memset(G,0,sizeof(G));
  for(int i=1;i<=n;i++)
    for(int j=1;j<=n;j++)
      if(b[i-1][j-1]=='O') addedge(i,j,2);
      else if(b[i-1][j-1]=='N') addedge(i,j,inf);
}

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

inline bool bfs(){
  for(int i=S;i<=T;i++) dis[i]=-1;
  while(!Q.empty()) Q.pop();
  Q.push(S); dis[S]=0;
  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;
}

class OldBridges{
public:
  string isPossible(vector<string> bridges, int a1, int a2, int an, int b1, int b2, int bn){
    n=bridges.size(); a1++; a2++; b1++; b2++;
    Pre(bridges);
    addedge(S,a1,2*an); //addedge(a1,S,0);
    addedge(a2,T,2*an); //addedge(T,a2,0);
    addedge(S,b2,2*bn); //addedge(b2,S,0);
    addedge(b1,T,2*bn); //addedge(T,b1,0);
    int flow=0;
    while(bfs()){
      for(int i=S;i<=T;i++) cur[i]=G[i];
      flow+=dfs(S,inf); 
    }
    if(flow!=2*(an+bn)) return "No";
    Pre(bridges);
    addedge(S,a1,2*an); //addedge(a1,S,0);
    addedge(a2,T,2*an); //addedge(T,a2,0);
    addedge(S,b1,2*bn); //addedge(b1,S,0);
    addedge(b2,T,2*bn); //addedge(T,b2,0);
    flow=0;
    while(bfs()){
      for(int i=S;i<=T;i++) cur[i]=G[i];
      flow+=dfs(S,inf);
    }
    if(flow!=2*(an+bn)) return "No";
    return "Yes";
  }
}Main;

int main(){
  vector<string> b=
    {"XXNXXX",
     "XXNXXX",
     "NNXOXX",
     "XXOXNN",
     "XXXNXX",
     "XXXNXX"};
  int a1=0;
  int a2=4;
  int an=1;
  int b1=1;
  int b2=3;
  int bn=1;
  cout<<Main.isPossible(b,a1,a2,an,b1,b2,bn);
  for(;;);
}
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页