如果从src到dec的路径中没有节点是奇数,那么我尝试打印Bob,然后打印Bob或打印Alex。有一个具有N个顶点和N-1个边的图形。 Q是您必须打印Bob或Alex的路径的路径。 对我来说,这段代码花费的时间约为26.000000秒。如何改善它。
并且可以实现该程序而无需递归。
static class Graph{
static ArrayList<Integer> arr[] ;
static int N;
public Graph(int N) {
this.N = N;
arr = new ArrayList[N];
for (int i=0;i<N;i++)
arr[i] = new ArrayList<>();
}
public void addEdge(int u, int v) {
arr[u-1].add(v-1);
arr[v-1].add(u-1);
}
}
static class Path{
int u;
int v;
public Path(int u, int v) {
super();
this.u = u-1;
this.v = v-1;
}
}
public static void main(String[] args) {
long beginTime = System.nanoTime();
Scanner sc= new Scanner(System.in);
int N= sc.nextInt();
int Q= sc.nextInt();
Graph g = new Graph(N);
for(int m=0;m<N-1;m++)
{
g.addEdge(sc.nextInt(),sc.nextInt());
}
List<Path> ll= new ArrayList<>();
for(int i=0;i<Q;i++)
{
ll.add(new Path(sc.nextInt(),sc.nextInt()));
}
ll.forEach(s->printAllPaths(g,s.u, s.v));
System.err.println("AmpleSyrup done in " + ((System.nanoTime() - beginTime) / 1e9) + " seconds.");
}
static void printAllPaths(Graph g,int s, int d)
{
boolean[] isVisited = new boolean[g.N];
ArrayList<Integer> pathList = new ArrayList<>();
pathList.add(s);
printAllPathsUtil(g,s, d, isVisited, pathList);
}
static void printAllPathsUtil(
Graph g,Integer u, Integer d,
boolean[] isVisited,
List<Integer> localPathList) {
isVisited[u] = true;
if (u.equals(d))
{
if(localPathList.size()%2==0)
System.out.println("Alex");
else
System.out.println("Bob");
isVisited[u]= false;
return ;
}
for (Integer i : g.arr[u])
{
if (!isVisited[i])
{ localPathList.add(i);
printAllPathsUtil(g,i, d, isVisited, localPathList);
localPathList.remove(i);
}
}
isVisited[u] = false;
}