[BZOJ2929] [POI1999] 동굴 등반(네트워크 흐름)

제목 설명


전송문

문제풀이


제목이 불분명하군요 = 1 출발과 n에 도착하는 쪽은 한 번만 갈 수 있고 나머지는 마음대로 할 수 있습니다.그럼 누드적인 네트워크 흐름은

코드

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;

const int max_n=205;
const int max_N=max_n+2;
const int max_m=max_n*max_n;
const int max_e=max_m*2;
const int INF=1e9;

int n,m,N,x;
int tot,point[max_N],next[max_e],v[max_e],remain[max_e];
int deep[max_N],num[max_N],last[max_N],cur[max_N];
int maxflow;
queue <int> q;

inline void addedge(int x,int y,int cap){
    ++tot; next[tot]=point[x]; point[x]=tot; v[tot]=y; remain[tot]=cap;
    ++tot; next[tot]=point[y]; point[y]=tot; v[tot]=x; remain[tot]=0;
}
inline void bfs(int t){
    for (int i=1;i<=N;++i) deep[i]=N;
    deep[t]=0;
    for (int i=1;i<=N;++i) cur[i]=point[i];
    while (!q.empty()) q.pop();
    q.push(t);

    while (!q.empty()){
        int now=q.front(); q.pop();
        for (int i=point[now];i!=-1;i=next[i])
          if (deep[v[i]]==N&&remain[i^1]){
            deep[v[i]]=deep[now]+1;
            q.push(v[i]);
          }
    }
}
inline int addflow(int s,int t){
    int now=t,ans=INF;
    while (now!=s){
        ans=min(ans,remain[last[now]]);
        now=v[last[now]^1];
    }
    now=t;
    while (now!=s){
        remain[last[now]]-=ans;
        remain[last[now]^1]+=ans;
        now=v[last[now]^1];
    }
    return ans;
}
inline void isap(int s,int t){
    bfs(t);
    for (int i=1;i<=N;++i) ++num[deep[i]];

    int now=s;
    while (deep[s]<N){
        if (now==t){
            maxflow+=addflow(s,t);
            now=s;
        }

        bool has_find=false;
        for (int i=cur[now];i!=-1;i=next[i])
          if (deep[v[i]]+1==deep[now]&&remain[i]){
            has_find=true;
            cur[now]=i;
            last[v[i]]=i;
            now=v[i];
            break;
          }

        if (!has_find){
            int minn=N-1;
            for (int i=point[now];i!=-1;i=next[i])
              if (remain[i]) minn=min(minn,deep[v[i]]);
            if (!(--num[deep[now]])) break;
            num[deep[now]=minn+1]++;
            cur[now]=point[now];
            if (now!=s) now=v[last[now]^1];
        }
    }
}

int main(){
    tot=-1;
    memset(point,-1,sizeof(point));
    memset(next,-1,sizeof(next));

    scanf("%d",&n);
    N=n+2;
    for (int i=1;i<n;++i){
        scanf("%d",&m);
        for (int j=1;j<=m;++j){
            scanf("%d",&x);
            if (i==1||x==n) addedge(1+i,1+x,1);
            else addedge(1+i,1+x,INF);
        }
    }
    addedge(1,2,INF);
    addedge(N-1,N,INF);
    isap(1,N);
    printf("%d
"
,maxflow); }

좋은 웹페이지 즐겨찾기