Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

不知为何,dinic算法,邻接表建双向边会超,单向边94ms

Posted by kg20006 at 2015-06-02 17:59:39 on Problem 1459 and last updated at 2015-06-03 21:25:40
#include<cstring>
#include<cstdio>
#include<queue>
#include<algorithm>
#define INF 0x7fffffff
using namespace std;
int n, np, nc, m;
int map[1005][1005];
int fir[20005],nex[20005],cnt;
int u[20005],v[20005];
int lev[1005];
void add(int a, int b){
    u[cnt] = a, v[cnt] = b;
    nex[cnt] = fir[a];
    fir[a] = cnt++;
}
bool Bfs(int s, int t){
    memset(lev, -1, sizeof(lev));
    queue<int>q;
    q.push(s);
    lev[s] = 0;
    while( !q.empty() ){
        int a = q.front(); q.pop();
        for(int k = fir[a]; k != -1; k = nex[k]){
            int b = v[k];
            if(map[a][b] && lev[b] == -1){
                lev[b] = lev[a] + 1;
                q.push(b);
            }
        }
    }
    return lev[t]>0;
}
int Dfs(int s, int t, int low){
    if(s==t) return low;
    int a=0;
    for(int k = fir[s]; k != -1; k = nex[k]){
        int b = v[k];
        if( map[s][b] && lev[s]+1 == lev[b] && ( a = Dfs(b, t, min(low,map[s][b]) ) )){
            map[s][b] -= a;
            map[b][s] += a;
            return a;
        }
    }
    lev[s] = -1;
    return 0;
}
void Dinic(int s, int t){
    int ans=0, a;
    while( Bfs(s, t) ){
        while( a = Dfs(s, t, INF) ) ans+=a;
    }
    printf("%d\n",ans);
}
int main(){
    int a,b,c;
    while( scanf("%d%d%d%d", &n, &np, &nc, &m) != EOF){
        cnt = 0;
        memset(map, 0,sizeof(map));
        memset(fir, -1, sizeof(fir));
        for(int i = 0; i < m; ++i){
            scanf(" (%d,%d)%d", &a, &b, &c);
            map[a+1][b+1] = c;
            add(a+1, b+1);
            //add(b+1, a+1);双向边就会超时
        }
        for(int i = 0; i < np; ++i){
            scanf(" (%d)%d", &b, &c);
            map[0][b+1] = c;
            add(0, b+1);
            //add(b+1, 0);
        }
        for(int i = 0;i < nc; ++i){
            scanf(" (%d)%d", &b, &c);
            map[b+1][n+1] = c;
            add(b+1, n+1);
            //add(n+1, b+1);
        }
        Dinic(0,n+1);
    }
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator