心如止水
Je n'ai pas le temps
posts - 400,comments - 130,trackbacks - 0
这是本人AC的第一道网络流建模的题目哇~内牛满面!!!做了两天才AC……
网络流题目重在构图
以下是我的代码:
#include<iostream>
#include
<string>
#include
<queue>
#include
<map>
#include
<algorithm>
#include
<cstdio>
#include
<cstring>
using namespace std;
const int kMaxn(507);
const int kInf(77777);

int a,b,c;
map
<string,int> r;
int n,source,sink,maxflow,cap[kMaxn][kMaxn],flow[kMaxn][kMaxn];

void SAP()
{
    
int d[kMaxn],num[kMaxn],p[kMaxn];

    memset(flow,
0,kMaxn*kMaxn*sizeof(int));
    memset(d,
0x7f,kMaxn*sizeof(int));
    memset(num,
0,kMaxn*sizeof(int));
    queue
<int> q;
    d[sink]
=0;
    num[
0]++;
    q.push(sink);
    
while(!q.empty())
    {
        
int v(q.front());q.pop();
        
for(int u=1;u<=n;u++)
            
if(d[u]>=&& cap[u][v]>flow[u][v])
            {
                d[u]
=d[v]+1;
                num[d[u]]
++;
                q.push(u);
            }
    }

    maxflow
=0;
    
int u(source),v;
    
while(d[source]<n)
    {
        v
=-1;
        
for(int i=1;i<=n;i++)
            
if(cap[u][i]>flow[u][i] && d[u]==d[i]+1)
            {v
=i;break;}
        
if(v!=-1)
        {
            p[v]
=u;u=v;
            
if(u==sink)
            {
                
int add(kInf);
                
for(u=sink;u!=source;u=p[u])
                    add
=min(add,cap[p[u]][u]-flow[p[u]][u]);
                maxflow
+=add;
                
for(u=sink;u!=source;u=p[u])
                {
                    flow[p[u]][u]
+=add;
                    flow[u][p[u]]
-=add;
                }
            }
        }
        
else
        {
            num[d[u]]
--;
            
if(!num[d[u]])
                
return;
            d[u]
=n;
            
for(v=1;v<=n;v++)
                
if(cap[u][v]>flow[u][v])
                    d[u]
=min(d[u],d[v]+1);
            num[d[u]]
++;
            
if(u!=source)
                u
=p[u];
        }
    }
}

int main()
{
    source
=1;
    sink
=2;
    n
=2;
    memset(cap,
0,kMaxn*kMaxn*sizeof(int));

    cin
>>a;
    
for(int i=1;i<=a;i++)
    {
        
string t;
        cin
>>t;
        r[t]
=(++n);
        cap[n][sink]
++;
    }
    cin
>>b;
    
for(int i=1;i<=b;i++)
    {
        
string t1,t2;
        cin
>>t1>>t2;
        r[t1]
=(++n);
        cap[source][n]
++;
        
if(!r.count(t2))
            r[t2]
=(++n);
        cap[r[t1]][r[t2]]
++;
    }
    cin
>>c;
    
for(int i=1;i<=c;i++)
    {
        
string t1,t2;
        cin
>>t1>>t2;
        
if(!r.count(t1))
            r[t1]
=(++n);
        
if(!r.count(t2))
            r[t2]
=(++n);
        cap[r[t1]][r[t2]]
=kInf;
    }

    SAP();

    printf(
"%d\n",b-maxflow);

    
return 0;
}
posted on 2011-05-31 19:47 lee1r 阅读(186) 评论(0)  编辑 收藏 引用 所属分类: 题目分类:图论

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理