Header Ad

HackerEarth AltF4 and Spinal Network problem solution

In this HackerEarth AltF4 and Spinal Network problem solution AltF4 is into his networking class and his teacher introduces him to bus topology. Being bored of the class, he his lost into his own thoughts where he discovers a new topology of his own - the Spinal Network. In this topology, we have a central line just like the bus topology. All the nodes (or hops, or computers) are either in the central line itself, or it is directly connected to the central line. To make things easier he says that the topology given should be a tree. Resembles the spinal cord, isn't it? Given a tree, you need to figure out if it is spinal or not.

HackerEarth AltF4 and Spinal Network problem solution

HackerEarth AltF4 and Spinal Network problem solution.

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Spinal {
public static void main(String args[]) throws IOException {
Scanner in = new Scanner(new FileReader("C://Users//Downloads//tree1.in"));
PrintWriter out = new PrintWriter(new FileWriter("C://Users//Downloads//tree1.out"));
int t = in.nextInt();
while(t-- > 0) {
int n = in.nextInt();
int degree[] = new int[n];
int edgeTo[] = new int[n];
int i;
for(i=1;i<n;i++) {
int u = in.nextInt() - 1, v = in.nextInt() - 1;
degree[u]++;//Increase degree of the vertex
degree[v]++;//Increase degree of the vertex
//Lets make a simplification here.
//We are bothered about only to find out leaf nodes
//So we store information of the node it has its edge to.
//If it has degree > 1, of course we are not going to check it.
edgeTo[u] = v;
edgeTo[v] = u;
boolean isLeaf[] = new boolean[n];
for(i=0;i<n;i++) {
if(degree[i] == 1) { //Leaf node
isLeaf[i] = true;
for(i=0;i<n;i++) {
if(isLeaf[i]) {
//Delete this edge
String isSpinal = "YES";
for(i=0;i<n;i++) {
if(degree[i] > 2) {
isSpinal = "NO";


Post a Comment