萌新dinic 4TLE 1WA求调

P3376 【模板】网络最大流

I_Was_Spasmodic @ 2024-02-28 17:12:13

用了dinic配链式前向星,自己对了一下模版感觉差不多,下数据本地跑发现WA的点半天跑不出来,很奇怪

传送门https://www.luogu.com.cn/record/148634920

代码如下


#include<bits/stdc++.h>
#define ll long long
using namespace std;
int n,m,s,t,top=1;
struct edge{
    int to,ne;
    ll w;
    edge(){}
    edge(int a,ll b,int c){to=a,w=b,ne=c;}
}e[100005];
int h[2005],now[2005],dep[2005];
void add_edge(int u,int v,ll w)
{
    e[++top]=edge(v,w,h[u]);
    h[u]=top;
}
bool bfs()
{
    for(int i=0;i<=n;i++)dep[i]=0;
    dep[s]=1;
    queue<int>q;
    q.push(s);
    while(!q.empty())
    {
        int x=q.front();
//      printf("now at %d ,dep=%d\n",x,dep[x]);
        q.pop();
        for(int i=h[x];i!=0;i=e[i].ne)
        {
//          printf("%d to %d(origin dep=%d) w=%d \n",x,e[i].to,dep[e[i].to],e[i].w);
            if(dep[e[i].to]==0 and e[i].w>0)
            {
                dep[e[i].to]=dep[x]+1;
                q.push(e[i].to);
//              printf("dep[%d]=%d\n",e[i].to,dep[e[i].to]);
                if(e[i].to==t)return 1;
//              else printf("compare %d and %d =>false\n",e[i].to,t);
//          for(int i=1;i<=n;i++)cout<<dep[i]<<' ';
//          cout<<'\n';
            }
        }
    }
    return 0;
}
ll dfs(int x,ll mf)
{
    if(x==t)return mf;
    ll sum=0;
    for(int i=now[x];i!=0;i=now[x]=e[i].ne)
    {
        if(dep[e[i].to]==dep[x]+1 and e[i].w>0)
        {
            int flow=dfs(e[i].to,min(mf,e[i].w));
            e[i].w-=flow;
            e[i^1].w+=flow;
            sum+=flow;
            mf-=flow;
            if(mf==0)break;
        }
    }
    if(sum==0)dep[x]=0;
    return sum;
}
ll dinic()
{
    ll tot=0;
    while(bfs())
    {
        for(int i=1;i<=top;i++)now[i]=h[i];
        tot+=dfs(s,INT_MAX);
//      printf("----\n");
    }
    return tot;
}
int main()
{
    cin>>n>>m>>s>>t;
    int u,v;
    ll w;
    while(m--)
    {
        cin>>u>>v>>w;
        add_edge(u,v,w);
        add_edge(v,u,0);
    }
    cout<<dinic();
}

by KellyFrog @ 2024-03-01 11:29:20

@I_Was_Spasmodic

for(int i=1;i<=top;i++)now[i]=h[i];

越界了,top=2m+1


by Catalan1906 @ 2024-03-01 13:10:19

@I_Was_Spasmodic 拜谢xjn神仙。


by I_Was_Spasmodic @ 2024-03-01 13:10:51

@KellyFrog ok过了,感谢大佬


by I_Was_Spasmodic @ 2024-03-01 13:12:49

@Le_temps_des_fleurs 别。


by Catalan1906 @ 2024-03-01 13:13:13

@I_Was_Spasmodic 你要进队,我要文化课


by I_Was_Spasmodic @ 2024-03-01 13:14:03

@Le_temps_des_fleurs 错误的,我进不了。


|