图论模板

来源:互联网 发布:javascript return; 编辑:程序博客网 时间:2024/05/17 02:23

一、图的建立与存储

1.邻接矩阵

struct Graph{    static maxn=1001;    int f[maxn][maxn];};

2.邻接表

二、网络流

1.最大流

Edmonds_Karp

struct Edmonds_Karp{    static const int maxn=10000+1,INF=0x7fffffff;    int n,m;    struct Edge    {        int from,to,cap,flow;        Edge(int f,int t,int c,int fl):from(f),to(t),cap(c),flow(fl){}    };    vector<Edge>edge;    vector<int>G[maxn];    int a[maxn],p[maxn];    void add_edge(int f,int t,int c)    {        edge.push_back(Edge(f,t,c,0));        edge.push_back(Edge(t,f,0,0));        m+=2;        G[f].push_back(m-2);        G[t].push_back(m-1);    }    int  maxflow(int s,int t)    {        int flow=0;        for(;;)        {            memset(a,0,sizeof(a));            queue<int>Q;            Q.push(s);            a[s]=INF;            while(!Q.empty())            {                int u=Q.front();Q.pop();                int len=G[u].size();                for(register int i=0;i<len;++i)                {                    Edge &e=edge[G[u][i]];                    if(!a[e.to]&&e.cap>e.flow)                    {                        p[e.to]=G[u][i];                        a[e.to]=min(a[u],e.cap-e.flow);                        Q.push(e.to);                    }                }                if(a[t])break;            }            if(!a[t])break;            for(register int i=t;i!=s;i=edge[p[i]].from)            {                edge[p[i]].flow+=a[t];                edge[p[i]^1].flow-=a[t];            }            flow+=a[t];        }        return flow;    }}graph;
0 0
原创粉丝点击