Chef and Reversing Solution

Problem

Sometimes mysteries happen. Chef found a directed graph with N vertices and M edges in his kitchen!

The evening was boring and chef has nothing else to do, so to entertain himself, Chef thought about a question "What is the minimum number of edges he needs to reverse in order to have at least one path from vertex 1 to vertex N, where the vertices are numbered from 1 to N.

Input

Each test file contains only one test case.

The first line of the input contains two space separated integers N and M, denoting the number of vertices and the number of edges in the graph respectively. The ith line of the next M lines contains two space separated integers Xi and Yi, denoting that the ith edge connects vertices from Xi to Yi.

Output

In a single line, print the minimum number of edges we need to revert. If there is no way of having at least one path from 1 to N, print -1.

Constraints

  • 1 ≤ N, M ≤ 100000 = 105
  • 1 ≤ Xi, Yi ≤ N
  • There can be multiple edges connecting the same pair of vertices, There can be self loops too i.e. Xi = Yi

Sample 1:

Input
Output
7 7
1 2 
3 2
3 4
7 4
6 2
5 6
7 5
2

Explanation:

We can consider two paths from 1 to 7:

  • 1-2-3-4-7
  • 1-2-6-5-7

In the first one we need to revert edges (3-2), (7-4). In the second one - (6-2), (5-6), (7-5). So the answer is min(2, 3) = 2.






Program :


 #include<stdio.h>

#include<stdlib.h>

#define MAXN 200007

#pragma warning (disable:4996)

int x[MAXN], y[MAXN], w[MAXN], fi[MAXN], ne[MAXN], vi[MAXN], st[MAXN], t[MAXN];

int main()

{

int n, m;

scanf("%d%d", &n, &m);

for (int i = 0; i <= 2 * n; i++)

fi[i] = -1;

for (int i = 1; i <= m; i++)

{

scanf("%d%d", &x[2 * i - 1], &y[2 * i - 1]);

ne[2 * i - 1] = fi[x[2 * i - 1]];

fi[x[2 * i - 1]] = 2 * i - 1;

w[2 * i - 1] = 0;

x[2 * i] = y[2 * i - 1];

y[2 * i] = x[2 * i - 1];

ne[2 * i] = fi[x[2 * i]];

fi[x[2 * i]] = 2 * i;

w[2 * i] = 1;

}

for (int i = 0; i <= 2 * n; i++)

vi[i] = 0;

for (int i = 0; i <= 2 * n; i++)

st[i] = MAXN;

st[1] = 0;

int now;

int h, ti;

h = 0;

ti = 1;

t[h] = 1;

st[1] = 0;

while (h != ti)

{

now = t[h];

vi[now] = 0;

for (int i = fi[now]; i != -1; i = ne[i])

{

if (st[now] + w[i] < st[y[i]])

{

st[y[i]] = st[now] + w[i];

if (!vi[y[i]])

{

t[ti] = y[i];

vi[y[i]] = 1;

ti = (ti + 1) % n;

}

}

}

h = (h + 1) % n;

}

if (st[n] == st[0])

printf("-1");

else

printf("%d", st[n]);

return 0;

}

Post a Comment

0 Comments