Pagini recente » Cod sursa (job #2330054) | Cod sursa (job #614556) | Cod sursa (job #2522001) | Cod sursa (job #123282) | Cod sursa (job #1786023)
#include <algorithm>
#include <fstream>
#include <vector>
#include <tuple>
using namespace std;
typedef tuple<int, int, int> Muchie;
typedef vector<vector<pair<int, int>>> Arbore;
int AflaRadacina(int x, vector<int> &tati)
{
int rad = x;
while (tati[rad] != 0)
rad = tati[rad];
while (x != rad) {
int urm = tati[x];
tati[x] = rad;
x = urm;
}
return rad;
}
inline bool CmpMuchii(const Muchie &a, const Muchie &b)
{
return get<2>(a) < get<2>(b);
}
void Leaga(int x, int rx, int y, int ry, vector<int> &tati)
{
if (rx == 0) rx = x;
if (ry == 0) ry = y;
tati[ry] = rx;
}
Arbore ConstruiesteAPM(vector<Muchie> &muchii, int n)
{
Arbore apm(n + 1);
vector<int> tati(n + 1, 0);
sort(muchii.begin(), muchii.end(), CmpMuchii);
for (auto &muchie : muchii) {
int x = get<0>(muchie);
int y = get<1>(muchie);
int cost = get<2>(muchie);
int radx = AflaRadacina(x, tati);
int rady = AflaRadacina(y, tati);
if (radx != rady || rady == 0) {
apm[x].push_back({y, cost});
apm[y].push_back({x, cost});
Leaga(x, radx, y, rady, tati);
}
}
muchii.clear();
return apm;
}
int CostDFS(int x, int y, const Arbore &arb, vector<bool> &viz)
{
int cost = 0;
viz[x] = true;
if (x != y) {
for (auto &muchie : arb[x]) {
if (!viz[muchie.first]) {
int cost_vecin = CostDFS(muchie.first, y, arb, viz);
if (viz[y]) {
cost = max(cost_vecin, muchie.second);
break;
}
}
}
}
return cost;
}
int CalculeazaCost(int x, int y, const Arbore &arb)
{
vector<bool> vizitat(arb.size(), false);
return CostDFS(x, y, arb, vizitat);
}
int main()
{
ifstream fin("radiatie.in");
ofstream fout("radiatie.out");
int n, m, k;
fin >> n >> m >> k;
vector<Muchie> muchii(m);
for (int i = 0; i < m; ++i)
fin >> get<0>(muchii[i]) >> get<1>(muchii[i]) >> get<2>(muchii[i]);
Arbore arbore = ConstruiesteAPM(muchii, n);
while (k--) {
int x, y;
fin >> x >> y;
fout << CalculeazaCost(x, y, arbore) << "\n";
}
return 0;
}