The problem description is from ACM Timus Online Judge. (1930. Ivan's Car)
My first idea is using BFS. But it keeps getting Wrong Answer at Test 6. Any hints to solve this? The following is my Java code.
import java.io.*;
import java.util.*;
class ss // BFS node to put in the Queue
{
public int id; // town id
public int depth; // how many gear changes
public int prev; // previous town
public ss(int _id, int _d, int _p)
{
this.id = _id;
this.depth = _d;
this.prev = _p;
}
}
public class tsss
{
static ArrayList<Integer>[] towns;
static ArrayList<Integer>[] tt;
static boolean[] vis; // has been visited before ?
static boolean up(int a, int b)
{
for (int i = 0; i < tt[a].size(); i ++)
{
if (tt[a].get(i) == b)
{
return true; // from this go uphill
}
}
return false; // from this go downhill
}
static boolean change(int p, int cur, int next)
{
if (p == -1)
{
return false; // at the beginning you can turn on any gear modes
}
return (up(p, cur) != up(cur, next));
}
static int search(int a, int b)
{
if (a == b)
{
return 0;
}
Queue q = new LinkedList<ss>();
q.add(new ss(a, 0, -1)); // push the first node
Arrays.fill(vis, false);
vis[a] = true;
while (q.size() > 0)
{
ss k = (ss)q.poll();
int x = k.id;
int prev = k.prev;
for (int i = 0; i < towns[x].size(); i ++) // its children nodes
{
int y = (int)towns[x].get(i);
if (y == b)
{
if (change(prev, x, y))
{
return k.depth + 1;
}
return k.depth;
}
if (!vis[y]) // not visited before
{
vis[y] = true;
if ((change(prev, x, y))) // one gear change
{
q.add(new ss(y, k.depth + 1, x));
}
else
{
q.add(new ss(y, k.depth, x));
}
}
}
}
return 0;
}
public static void main(String[] args) throws IOException
{
BufferedReader rr = new BufferedReader(new InputStreamReader(System.in));
String[] s = rr.readLine().split(" ");
int n = Integer.parseInt(s[0]);
int m = Integer.parseInt(s[1]);
towns = new ArrayList[n + 1];
tt = new ArrayList[n + 1];
vis = new boolean[n + 1];
for (int i = 0; i < n + 1; i ++)
{
tt[i] = new ArrayList<Integer>();
towns[i] = new ArrayList<Integer>();
}
for (int i = 0; i < m; i ++)
{
s = rr.readLine().split(" ");
int x = Integer.parseInt(s[0]);
int y = Integer.parseInt(s[1]);
towns[x].add(y);
tt[x].add(y);
towns[y].add(x);
}
s = rr.readLine().split(" ");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
System.out.print(search(a, b));
}
}