Pagini recente » Cod sursa (job #3040426) | Cod sursa (job #1477959) | Cod sursa (job #72104) | Cod sursa (job #2043516) | Cod sursa (job #67673)
Cod sursa(job #67673)
#include <stdio.h>
#include <vector>
using namespace std;
#define maxn 32010
#define pb push_back
#define maxx 100010
int n,m,l;
vector <short> a[maxn],b[maxn];
vector <char> c[maxn];
short g[maxn];
short px[maxx],py[maxx],sol[maxx];
short cost[maxn],h[maxn],p[maxn];
void pop(int x)
{
int aux;
while ((x/2>1) && (cost[h[x]]<cost[h[x/2]]))
{
aux=h[x];
h[x]=h[x/2];
h[x/2]=aux;
p[h[x]]=x;
p[h[x/2]]=x/2;
x=x/2;
}
}
void push(int x)
{
int aux,y=0;
while (x!=y)
{
y=x;
if ((y*2<=l) && (cost[h[x]]>cost[h[y*2]])) x=y*2;
if ((y*2+1<=l) && (cost[h[x]]>cost[h[y*2+1]])) x=y*2+1;
aux=h[x];
h[x]=h[y];
h[y]=aux;
p[h[x]]=x;
p[h[y]]=y;
}
}
void Dijkstra(int nod)
{
int i;
for (i=1;i<=n;i++)
{
cost[i]=maxn;
h[i]=i;
p[i]=i;
}
cost[nod]=0;
h[1]=nod;
h[nod]=1;
p[1]=nod;
p[nod]=1;
l=n;
while (l>0)
{
for (i=0;i<g[h[1]];i++)
if (cost[h[1]]+c[h[1]][i]<cost[a[h[1]][i]])
{
cost[a[h[1]][i]]=cost[h[1]]+c[h[1]][i];
pop(p[a[h[1]][i]]);
}
p[h[1]]=0;
h[1]=h[l];
p[h[1]]=1;
h[l]=0;
l--;
if (l>1) push(1);
}
}
int main()
{
freopen("obiective.in","r",stdin);
freopen("obiective.out","w",stdout);
scanf("%d %d ",&n,&m);
int i,x,y,aux,j;
for (i=1;i<=m;i++)
{
scanf("%d %d ",&x,&y);
a[x].pb(y);
a[y].pb(x);
c[x].pb(0);
c[y].pb(1);
}
for (i=1;i<=n;i++) g[i]=a[i].size();
scanf("%d ",&m);
for (i=1;i<=m;i++)
{
scanf("%d %d ",&px[i],&py[i]);
b[px[i]].pb(i);
}
for (i=1;i<=n;i++)
{
aux=b[i].size();
if (aux>0)
{
Dijkstra(i);
for (j=0;j<aux;j++) sol[b[i][j]]=cost[py[b[i][j]]];
}
}
for (i=1;i<=m;i++) printf("%d\n",sol[i]);
return 0;
}