Pagini recente » Cod sursa (job #3230481) | Cod sursa (job #2859338) | Cod sursa (job #3146672) | Cod sursa (job #1202007) | Cod sursa (job #177287)
Cod sursa(job #177287)
#include <fstream>
#include <vector>
#define INF -1
#define MAX 15001
#define maxi(a, b) ((a) > (b) ? (a) : (b))
using namespace std;
vector<vector<int> > v;
struct Muchie{
int v1, v2, c;
};
struct Cmp{
bool operator () (Muchie a, Muchie b)
{
return (a.c < b.c);
}
};
Muchie g[MAX];
int n, m, K, cnt = 0;
int s[MAX], h[MAX], mul[MAX], hh[MAX], tata[MAX], co[MAX][MAX];
int e[MAX<<1], l[MAX<<1], a[MAX<<1][20], lg[MAX<<1];
int Find(int x)
{
if (x != mul[x]) mul[x] = Find(mul[x]);
return mul[x];
}
void Union(int x, int y)
{
if (mul[x] > mul[y]) mul[y] = mul[x];
else
{
mul[x] = mul[y];
if (hh[x] == hh[y]) hh[y]++;
}
}
void DF(int nod, int lvl)
{
s[nod] = 1;
e[++cnt] = nod;
l[cnt] = lvl;
if (!h[nod]) h[nod] = cnt;
int x = v[nod].size(), i;
for (i = 0; i < x; i++)
if (!s[v[nod][i]])
{
tata[v[nod][i]] = nod;
DF(v[nod][i], lvl+1);
e[++cnt] = nod;
l[cnt] = lvl;
}
}
int GetCMax(int x, int lca)
{
int cmax = 0;
if (x == lca) return INF;
while(x != lca)
{
cmax = maxi(cmax, co[tata[x]][x]);
x = tata[x];
}
return cmax;
}
int main()
{
int i, j, x, y, k = 0, cost;
ifstream fin("radiatie.in");
fin >> n >> m >> K;
v.resize(n+1);
for (i = 1; i <= n; i++) { mul[i] = i; hh[i] = 0; }
for (i = 1; i <= m; i++)
fin >> g[i].v1 >> g[i].v2 >> g[i].c;
sort(g+1, g+m+1, Cmp());
for (i = 1; i <= m; i++)
{
x = Find(g[i].v1);
y = Find(g[i].v2);
if (x != y)
{
Union(x, y);
v[g[i].v1].push_back(g[i].v2);
v[g[i].v2].push_back(g[i].v1);
co[g[i].v1][g[i].v2] = co[g[i].v2][g[i].v1] = g[i].c;
}
}
DF(1, 1);
lg[1] = 0;
for (i = 2; i <= cnt; i++)
lg[i] = lg[i/2] + 1;
for (i = 1; i <= cnt; i++)
a[i][0] = i;
for (j = 1; (1 << j) <= cnt; j++)
for (i = 1; i + (1 << (j-1)) <= cnt; i++)
{
x = i + (1 << (j-1));
if (l[a[i][j-1]] < l[a[x][j-1]]) a[i][j] = a[i][j-1];
else a[i][j] = a[x][j-1];
}
ofstream fout("radiatie.out");
/* fout << "E: ";
for (i = 1; i <= cnt; i++)
fout << e[i] << " ";
fout << "\nL: ";
for (i = 1; i <= cnt; i++)
fout << l[i] << " ";
fout << "\nH: ";
for (i = 1; i <= n; i++)
fout << h[i] << " ";
fout << "\n";
*/
int max1, max2, lca;
for (; K; K--)
{
fin >> x >> y;
k = lg[y-x];
if (l[a[x][k]] < l[a[y-(1<<k)+1][k]]) lca = e[a[x][k]];
else lca = e[a[y-(1<<k)+1][k]];
//fout << lca << " ";
max1 = GetCMax(x, lca);
max2 = GetCMax(y, lca);
fout << maxi(max1, max2) << "\n";
}
fin.close();
fout.close();
return 0;
}