Write java program following 4 5 0 1 c 0 3 c 0 1 1 3 c 0 3 expected output yes yes

QuestionsCategory: Computer ScienceWrite java program following 4 5 0 1 c 0 3 c 0 1 1 3 c 0 3 expected output yes yes
Jimmy asked 1 year ago

Write a Java program, that can do the following:

4 5
A 0 1
C 0 3
C 0 1
A 1 3
C 0 3
Expected Output
NO
YES
YES

1 Answers
Techtuna Staff answered 1 year ago

//Here is your answer..
package JavaApplication10;
import java.util.Scanner;
public class MyProgram
{
public static void main(String[] agrs)
{
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
int M=sc.nextInt();
char operation;
int s,d;
int[] arr=new int[1000000];//array for input
//initialize array with -1
for(int i=0;i<N;i++)
arr[i]=-1;
for(int i=0;i<M;i++)
{
operation=sc.next().charAt(0);
s=sc.nextInt();
d=sc.nextInt();
if(operation==’A’)
{
int j=s<d?s:d;
//check if connected or not
while(arr[j]!=-1 && arr[j]!=d)
{
j=arr[j];
}
//if not connected then connect
if(arr[j]==-1)
arr[j]=d;
}
else
{
int j=s<d?s:d;
//check both connected or not
while(arr[j]!=-1 && arr[j]!=d)
{
j=arr[j];
}
//print result
if(arr[j]==d)
System.out.println(“YES”);
  
else
System.out.println(“NO”);   
}
}
}
}
//output
JavaApplication10-NetBeans IDE 8.1 File Edit View Navigate Source Refactor Run Debug Profile Teem Tools Window Help Seardh (C