Pagini recente » Cod sursa (job #3191092) | Cod sursa (job #1154764) | Cod sursa (job #1210348) | Cod sursa (job #2138834) | Cod sursa (job #389914)
Cod sursa(job #389914)
# include <fstream>
# include <iostream>
# define INFINIT 1000000000
using namespace std;
struct nod {
int capat, cost;
nod *next;};
nod *a[15003];
int n, h[15003], poz[15003], d[15003], v[15003], nh, t[15003], gr[15003];
void add (int i, int j, int c)
{
nod *p=new nod;
p->capat=j;
p->cost=c;
p->next=a[i];
a[i]=p;
}
void cerne (int k, int n)
{
int eh=0, i;
while (!eh && 2*k<=n)
{
i=2*k;
if (i+1<=n && d[h[i+1]]<d[h[i]])
i++;
if (d[h[i]]>=d[h[k]])
eh=1;
else
{
int aux;
aux=h[i], h[i]=h[k], h[k]=aux;
poz[h[i]]=i;
poz[h[k]]=k;
k=i;
}
}
}
void promoveaza (int k)
{
int eh=0;
while (!eh && k/2)
if (d[h[k]]>=d[h[k/2]])
eh=1;
else
{
int aux;
aux=h[k], h[k]=h[k/2], h[k/2]=aux;
poz[h[k]]=k;
poz[h[k/2]]=k/2;
k/=2;
}
}
void initializeaza ()
{
for (int i=1;i<=n;i++)
d[i]=INFINIT, h[i]=i, poz[i]=i, v[i]=0, t[i]=-1;
nh=n;
}
void prim (int sursa)
{
int max=-1;
initializeaza ();
h[sursa]=h[nh];
poz[h[sursa]]=sursa;
nh--;
t[sursa]=0;
cerne (sursa, nh);
for (nod *p=a[sursa];p;p=p->next)
{
d[p->capat]=p->cost;
promoveaza(poz[p->capat]);
}
d[sursa]=0, v[sursa]=1;
for (int kk=1;kk<n;kk++)
{
int P;
P=h[1];
v[P]=1;
h[1]=h[nh];
poz[h[1]]=1;
nh--;
cerne(1, nh);
if (d[P]>max)
max=d[P];
for (nod *p=a[P];p;p=p->next)
if (v[p->capat]==0 && d[p->capat]>p->cost)
{
d[p->capat]=p->cost;t[p->capat]=P;gr[p->capat]=gr[P]+1;
promoveaza(poz[p->capat]);
}
}
}
int dist (int i, int j)
{
int max;
if (gr[i]>gr[j])
max=d[i];
else
max=d[j];
if (gr[i]<gr[j])
while (gr[j]>gr[i])
{
if (d[j]>max)
max=d[j];
j=t[j];
}
else
if (gr[j]<gr[i])
while (gr[i]>gr[j])
{
if (d[i]>max)
max=d[i];
i=t[i];
}
while (t[i]!=t[j])
{
if (d[i]>max)
max=d[i];
else
if (d[j]>max)
max=d[j];
i=t[i];
j=t[j];
}
return max;
}
int main ()
{
ifstream fin ("radiatie.in");
ofstream fout ("radiatie.out");
int m, k;
fin>>n>>m>>k;
for (;m;--m)
{
int x, y, c;
fin>>x>>y>>c;
add(x, y, c);
add(y, x, c);
}
prim(1);
for (;k;--k)
{
int sursa, dest;
fin>>sursa>>dest;
fout<<dist(sursa, dest)<<endl;
}
return 0;
}