Pagini recente » Cod sursa (job #68668) | Cod sursa (job #29391) | Cod sursa (job #2399047) | Cod sursa (job #1809180) | Cod sursa (job #3188708)
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
#include <cmath>
#include <iomanip>
#include <algorithm>
#include <climits>
using namespace std;
ifstream fin("harta.in");
ofstream fout("harta.out");
ifstream fin1("cc.in");
ofstream fout2("cc.out");
class Solution
{
public:
void taramul_nicaieri()
{
int n;
fin >> n;
vector<int> in (n + 1);
vector<int> out (n + 1);
int roads = 0;
for(int i = 1; i <= n; i++)
{
fin >> out[i] >> in[i];
roads += out[i];
}
fout << roads << '\n';
for(int i = 1; i <= n; ++i)
{
vector<pair<int, int>> v;
for(int j = 1; j <= n; j++)
v.push_back({in[j], j});
sort(v.begin(), v.end(), [](pair<int, int> a, pair<int, int> b) ///sort after in degree for each iteration
{
if(a.first == b.first)
return a.second > b.second;
return a.first > b.first;
});
for(int j = 0 ; j < n && out[i] ; j++)
if(v[j].second != i) /// if we have different nodes
{
fout << i << ' ' << v[j].second << '\n';
out[i]--;
in[v[j].second]--;
}
}
}
void cc()
{
int i, j, k, n, costs[202][202], capacity[202][202], flux[202][202], o[202], h[202], cc[10001], p, q, t, l; /// h for height, o for growth roads
long long total = 0;
fin1 >> n;
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++)
{
fin1 >> k;
costs[i][n + j + 1] = k; /// build costs
costs[n + j + 1][i] = -k;
capacity[i][n + j + 1] = 1; /// build capacity
}
for(i = 1; i <= n; i++)
{
capacity[0][i] = capacity[i + n + 1][n + 1] = 1;
costs[0][i] = costs[i + n + 1][n + 1] = 0;
}
///BFS
while(true)
{
for(i = 1; i <= 2 * n + 1; i ++)
{
o[i] = 0;
h[i] = 10001;
}
h[0] = 0; /// set height at 0
p = 0; ///p, q, cc for BFS
q = 0;
cc[q++] = 0;
while(p < q)
{
t = cc[p++]; /// pick the last from cc like a queue
if(t && t <= n) /// check if t is source
{
for(i = n + 1; i <= 2 * n + 1; i++)
if(flux[t][i] < capacity[t][i] && h[i] > h[t] + costs[t][i]) /// if the flux[t][i] can be bigger
{
cc[q++] = i;
o[i] = t;
h[i] = h[t] + costs[t][i];
}
}
else /// t is a destination
for(i = 1; i <= n + 1; i++)
if(flux[t][i] < capacity[t][i] && h[i] > h[t] + costs[t][i]) /// if the flux[t][i] can be bigger
{
cc[q++] = i;
o[i] = t;
h[i] = h[t] + costs[t][i];
}
}
if(!o[n+1]) /// if we have no growth roads
break;
/// we update the flux matrix
for(l = n + 1; l != 0; l = o[l])
{
flux[o[l]][l]++; /// increase the flux on edge
flux[l][o[l]]--; /// decrease the flux
}
total += h[n + 1]; ///total cost
}
fout2 << total;
}
};
int main()
{
Solution a;
a.cc();
}