Pagini recente » Cod sursa (job #3032469) | Cod sursa (job #3200772) | Cod sursa (job #3197534)
#include <bits/stdc++.h>
#define int long long
using namespace std;
ifstream fin("traseu.in");
ofstream fout("traseu.out");
const int INF=1e9;
int n,m,ans;
int S,D,cap[65][65],cost[65][65];
int out[65],in[65];
vector<int> muchii[65];
int dist[65],from[65];
bool flux()
{
for(int i=1;i<=n+2;i++)
{
dist[i]=INF;
from[i]=0;
}
dist[S]=0;
queue<int> coada;
coada.push(S);
while(!coada.empty())
{
int nod=coada.front();
coada.pop();
for(int i:muchii[nod])
if(cap[nod][i]>0&&dist[i]>dist[nod]+cost[nod][i])
{
dist[i]=dist[nod]+cost[nod][i];
from[i]=nod;
coada.push(i);
}
}
if(dist[D]==INF)
return 0;
int minim=INF;
for(int i=D;i!=S;i=from[i])
minim=min(minim,cap[from[i]][i]);
ans+=minim*dist[D];
for(int i=D;i!=S;i=from[i])
{
cap[from[i]][i]-=minim;
cap[i][from[i]]-=minim;
}
return 1;
}
signed main()
{
ios_base::sync_with_stdio(false);
fin.tie(0);
fin>>n>>m;
for(int i=1;i<=m;i++)
{
int a,b,c;
fin>>a>>b>>c;
cap[a][b]=INF;
cap[b][a]=0;
cost[a][b]=c;
cost[b][a]=-c;
out[a]++;
in[b]++;
ans+=c;
muchii[a].push_back(b);
muchii[b].push_back(a);
}
S=n+1;
D=n+2;
for(int nod=1;nod<=n;nod++)
{
if(in[nod]>out[nod])
{
cap[S][nod]=in[nod]-out[nod];
muchii[S].push_back(nod);
muchii[nod].push_back(S);
}
if(out[nod]>in[nod])
{
cap[nod][D]=out[nod]-in[nod];
muchii[nod].push_back(D);
muchii[D].push_back(nod);
}
}
while(flux());
fout<<ans;
return 0;
}