Electrical grid

ou j ai le prob
import java.util.;
import java.io.
;
import java.math.*;

class Solution {

public static void main(String args[]) {
    Scanner in = new Scanner(System.in);
    int N = in.nextInt();
    int M = in.nextInt();
    Cost[] tblCost = new Cost[M];
    ArrayList tblSol = new ArrayList();
    
    for (int i = 0; i < M; i++) {
        int house1 = in.nextInt();
        int house2 = in.nextInt();
        int cost = in.nextInt();
        
        tblCost[i] = new Cost(house1,house2,cost);
    }
    
    Arrays.sort(tblCost, new Comparator<Cost>() {
        @Override
        public int compare(Cost o1, Cost o2) {
            return o1.compareTo(o2);
        }
    });
    
    
    for (int i = 0; i < M; i++) {
        if(i==0){
            tblSol.add(tblCost[i]);
        }
        else
        {
            boolean bHouse1 = false;
            boolean bHouse2 = false;
            for (int j = 0; j < i; j++){
                bHouse1 = bHouse1 || (tblCost[i].house1 == tblCost[j].house1) ;
                bHouse1 = bHouse1 || (tblCost[i].house1 == tblCost[j].house2) ;
                
                bHouse2 = bHouse2 || (tblCost[i].house2 == tblCost[j].house1) ;
                bHouse2 = bHouse2 || (tblCost[i].house2 == tblCost[j].house2) ;
                
                
            }
            
            if(!(bHouse1 && bHouse2)){
                tblSol.add(tblCost[i]);
            }
        }
    }
    
    
    Collections.sort(tblSol, new Comparator<Cost>() {
        @Override
        public int compare(Cost o1, Cost o2) {
            return o1.compareTo2(o2);
        }
    });
    
    int totCos = 0;
    for(int i = 0; i < tblSol.size(); i++){
        Cost c = (Cost)tblSol.get(i);
        totCos += c.cost;
    }
    
    System.out.println(tblSol.size() + " " + totCos);
    for(int i = 0; i < tblSol.size(); i++){
        System.out.println(tblSol.get(i));
        Cost c = (Cost)tblSol.get(i);
    }        
    
}

}

class Cost
{
int house1;
int house2;
int cost;

public  Cost(int house1,int house2,int cost){
    this.house1 = house1;
    this.house2 = house2;
    this.cost = cost;
    
}

public int compareTo(Cost obj){
    return (this.cost-obj.cost);
}

public int compareTo2(Cost obj){
    if(this.house1!=obj.house1)return (this.house1-obj.house1);
    if(this.house2!=obj.house2)return (this.house2-obj.house2);
    return (this.cost-obj.cost);
}
public String toString(){
    return (house1 +" "+ house2 +" "+ cost);
}

}

If you’re writing about the NetWork Cabling puzzle, please use the related thread

Also, don’t ask people to fix your code; explain what blocks you and what you tried to do to find a solution.

EDIT it seems you’re talking about the puzzle of the week, so ignore my first sentence.

1 Like