Pagini recente » Cod sursa (job #138536) | Cod sursa (job #1252666) | Cod sursa (job #1471528) | Cod sursa (job #392691) | Cod sursa (job #3151520)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
class InParser {
private:
FILE *fin;
char *buff;
int sp;
char read_ch() {
++sp;
if (sp == 4096) {
sp = 0;
fread(buff, 1, 4096, fin);
}
return buff[sp];
}
public:
InParser(const char* nume) {
fin = fopen(nume, "r");
buff = new char[4096]();
sp = 4095;
}
InParser& operator >> (int &n) {
char c;
while (!isdigit(c = read_ch()) && c != '-');
int sgn = 1;
if (c == '-') {
n = 0;
sgn = -1;
} else {
n = c - '0';
}
while (isdigit(c = read_ch())) {
n = 10 * n + c - '0';
}
n *= sgn;
return *this;
}
InParser& operator >> (long long &n) {
char c;
n = 0;
while (!isdigit(c = read_ch()) && c != '-');
long long sgn = 1;
if (c == '-') {
n = 0;
sgn = -1;
} else {
n = c - '0';
}
while (isdigit(c = read_ch())) {
n = 10 * n + c - '0';
}
n *= sgn;
return *this;
}
};
InParser fin("fmcm.in");
ofstream fout("fmcm.out");
vector<int> x[351];
pair<int, int> h[351][351];
int dist[351], init[351][351], prec[351], p[351], sol;
int F(int a)
{int mini=1e4;
while(prec[a]!=-1)
{mini=min(mini, h[prec[a]][a].first);
a=prec[a];
}
return mini;
}
void update(int a, int v)
{while(prec[a]!=-1)
{h[prec[a]][a].first-=v, sol+=v*init[prec[a]][a];
h[a][prec[a]].first+=v, sol-=v*init[a][prec[a]];
a=prec[a];
}
}
struct Data{
int a;
bool operator <(const Data& other) const
{
return dist[a]>dist[other.a];
}
};
int main()
{ ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int n, m, a, b, c, d, s, f;
fin>>n>>m>>s>>f;
for(int i=1;i<=m;i++)
{fin>>a>>b>>c>>d;
init[a][b]=d;
x[a].push_back(b), x[b].push_back(a);
h[a][b]={c, d};
h[b][a]={0, -d};
}
for(int i=1;i<=n;i++)
dist[i]=1e4;
dist[s]=0, p[s]=1, prec[s]=-1;
queue<int> q;
priority_queue<Data> q1;
vector<int>:: iterator I;
q.push(s);
while(q.empty()!=1)
{a=q.front();
p[a]=0;
for(I=x[a].begin();I<x[a].end();I++)
if(h[a][*I].first>0 && dist[*I]>dist[a]+h[a][*I].second)
{prec[*I]=a;
dist[*I]=dist[a]+h[a][*I].second;
if(p[*I]==0)p[*I]=1, q.push(*I);
}
q.pop();
}
if(dist[f]!=1e4)
{int v=F(f);
update(f, v);
for(int i=1;i<=n;i++)
for(I=x[i].begin();I<x[i].end();I++)
h[i][*I].second+=dist[i]-dist[*I];
}
while(dist[f]!=1e4)
{for(int i=1;i<=n;i++)
dist[i]=1e4, p[i]=0;
dist[s]=0;
q1.push({s}), p[s]=1, prec[s]=-1;
while(q1.empty()!=1)
{a=q1.top().a;
p[a]=0;
for(I=x[a].begin();I<x[a].end();I++)
if(h[a][*I].first>0 && dist[*I]>dist[a]+h[a][*I].second)
{dist[*I]=dist[a]+h[a][*I].second, prec[*I]=a;
if(p[*I]==0)p[*I]=1, q1.push({*I});
}
q1.pop();
}
if(dist[f]!=1e4)
{int v=F(f);
update(f, v);
for(int i=1;i<=n;i++)
for(I=x[i].begin();I<x[i].end();I++)
h[i][*I].second+=dist[i]-dist[*I];
}
}
fout<<sol;
return 0;
}