好久没写费用流的题了,今天有道贪心+搜索的题一开始以为是费用流,但是当时就忘记费用流题该怎么做了,找了道题做,发现这个和梁神模版一模一样的,然后我就当是练习敲模版了……这题RE好几次,我的MAXN开始开成1005,RE了,后来我扩大10倍还是RE,感觉好不科学……ps:好吧,现在我知道了,刚才POJ崩了,现在改成1005也不RE了
#include <cstdio>
#include <cstring>
#include <queue>
#include <iostream>
using namespace std;
#define MAXN 20005
#define MAXM 40050
#define inf 1<<30
struct Edge
{
int u,v,cap,cost,next;
};
int ans,n,m,sum,head[MAXN],pre[MAXN];
int used[MAXN],dist[MAXN];
Edge edge[MAXM];
void add(int a,int b,int cap,int cost)
{
edge[sum].u=a;
edge[sum].v=b;
edge[sum].cap=cap;
edge[sum].cost=cost;
edge[sum].next=head[a];
head[a]=sum++;
}
void addedge(int a,int b,int cap,int cost)
{
add(a,b,cap,cost);
add(b,a,0,-cost);
}
int spfa()
{
queue<int> q;
q.push(0);
memset(used,0,sizeof(used));
used[0]=1;
memset(pre,-1,sizeof(pre));
for(int i=1;i<=n;i++)
dist[i]=inf;
dist[0]=0;
while(!q.empty())
{
int u=q.front();
used[u]=0;
q.pop();
for(int i=head[u];i>=0;i=edge[i].next)
{
int v=edge[i].v;
if(edge[i].cap>0&&dist[u]+edge[i].cost<dist[v])
{
dist[v]=dist[u]+edge[i].cost;
if(!used[v])
{
used[v]=true;
q.push(v);
}
pre[v]=i;
}
}
}
if(dist[n]!=inf)
return 1;
else return 0;
}
int min_cost()
{
int res=0,maxflow=inf;
while(spfa())
{
for(int i=pre[n];i>=0;i=pre[edge[i].u])
if(edge[i].cap<maxflow)
maxflow=edge[i].cap;
for(int i=pre[n];i>=0;i=pre[edge[i].u])
{
res+=maxflow*edge[i].cost;
edge[i].cap-=maxflow;
edge[i^1].cap+=maxflow;
}
}
return res;
}
int main()
{
scanf("%d%d",&n,&m);
sum=0;
memset(head,-1,sizeof(head));
for(int i=0;i<m;i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
addedge(a,b,1,c);
addedge(b,a,1,c);
}
addedge(0,1,2,0);
addedge(n,n+1,2,0);
n++;
ans=min_cost();
printf("%d\n",ans);
}