I run the below code on my desktop it shows correct answer for the given test cases…but on submitting, i got wrong answer !
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
class Travel {
public static void main(String arg[])throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int nc = Integer.parseInt(br.readLine());
String cities[] = new String[nc];
cities = br.readLine().split(" ");
Arrays.sort(cities);
// System.out.println(Arrays.toString(cities));
int map[][] = new int[nc][nc];
int nr = Integer.parseInt(br.readLine());
String mapip[] = new String[3];
for(int i=0;i<nr;i++)
{
mapip = br.readLine().split(" ");
String fromCityName = mapip[0];
String toCityName = mapip[1];
int fromCityIndex = Arrays.binarySearch(cities,fromCityName);
int toCityIndex = Arrays.binarySearch(cities,toCityName);
map[fromCityIndex][toCityIndex] = Integer.parseInt(mapip[2]);
}
// System.out.println(Arrays.toString(mapip));
// System.out.println("enter no. of routes");
int nroute = Integer.parseInt(br.readLine());
String route[]={""};
int nor =0;
for(int i=0;i<nroute;i++)
{
boolean visited[] =new boolean[nc];
StringTokenizer st = new StringTokenizer(br.readLine());
while(st.hasMoreTokens()){
nor = Integer.parseInt(st.nextToken());
route = new String[nor];
for(int j=0;j<nor;j++)
route[j]=st.nextToken();
}
int t=0,prev=0,cost=0;
boolean flag =true;
if((t =Arrays.binarySearch(cities,route[0]))>=0)
{
prev=t;
visited[t]=true;
}
for(int k=1;k<nor;k++)
{
if((t =Arrays.binarySearch(cities,route[k]))>=0)
{
if(!visited[t]&& map[prev][t]>0)
{
cost+=map[prev][t];
visited[t]=true;
prev=t;
}
else
{
flag=false;
break;
}
}
else
{
flag=false;
break;
}
}
if(flag)
System.out.println(cost);
else
System.out.println("ERROR");
}
}
}