Pagini recente » Cod sursa (job #3334711) | Cod sursa (job #3331028) | Cod sursa (job #1128259) | Cod sursa (job #2423159) | Cod sursa (job #3304831)
#include <bits/stdc++.h>
using namespace std;
#define ST_DIO 0
#if ST_DIO
#define fin cin
#define fout cout
#else
ifstream fin("traseu.in");
ofstream fout("traseu.out");
#endif // ST_DIO
const int INF = 1e9 + 7;
struct Muchie {
int vec, cost;
};
int n, m, i, j, st, sf, flux[62][62], rasp;
int tata[62], cost[62];
int gradIn[62], gradOut[62];
vector<Muchie> gr[62];
bool fr[62];
static inline bool Dijkastra() {
for(int i = st; i <= sf; i++) cost[i] = INF;
memset(fr, false, sizeof(fr));
queue<int> q;
cost[st] = 0;
fr[st] = true;
q.push(st);
while(!q.empty()) {
int nod = q.front();
q.pop();
fr[nod] = false;
for(Muchie urm : gr[nod]) {
int costUrm = urm.cost + cost[nod];
if(costUrm < cost[urm.vec] && flux[nod][urm.vec] > 0) {
cost[urm.vec] = costUrm;
tata[urm.vec] = nod;
if(!fr[urm.vec]) {
fr[urm.vec] = true;
q.push(urm.vec);
}
}
}
}
return cost[sf] != INF;
}
static inline void BackTrack() {
int cur = sf;
int ma = INF;
while(cur != st) {
ma = min(ma, flux[tata[cur]][cur]);
cur = tata[cur];
}
cur = sf;
while(cur != st) {
flux[tata[cur]][cur] -= ma;
flux[cur][tata[cur]] += ma;
cur = tata[cur];
}
rasp += cost[sf] * ma;
}
int main() {
if(ST_DIO) ios_base::sync_with_stdio(false);
fin.tie(nullptr);
fout.tie(nullptr);
fin >> n >> m;
st = 0;
sf = n + 1;
for(i = 1; i <= m; i++) {
int x, y, c;
fin >> x >> y >> c;
gr[x].push_back({y, c});
gr[y].push_back({x, -c});
flux[x][y] = INF;
rasp += c;
gradOut[x]++;
gradIn[y]++;
}
for(i = 1; i <= n; i++) {
if(gradIn[i] > gradOut[i]) {
gr[st].push_back({i, 0});
gr[i].push_back({st, 0});
flux[st][i] = gradIn[i] - gradOut[i];
}
else {
gr[i].push_back({sf, 0});
gr[sf].push_back({i, 0});
flux[i][sf] = gradOut[i] - gradIn[i];
}
}
while(Dijkastra())
BackTrack();
fout << rasp;
return 0;
}