Untitled

mail@pastecode.io avatar
unknown
java
6 months ago
2.3 kB
8
Indexable
Never
//package counting_room_ces;
 
import java.io.*;
import java.util.*;
//building teams
public class countingRoom {
    static int n;
    static int m;
    static boolean[] visited ;
    static List<List<Integer>> adjList;
    static boolean[] color;
    public static void main(String[] args) throws IOException {
        // Redirect standard input
        BufferedReader reader;

             reader= new BufferedReader(new InputStreamReader(System.in));
 
            // Read n and m from the input file
            String s =reader.readLine();
        String a[]=s.split(" ");
        int n=Integer.parseInt(a[0]);
        int m=Integer.parseInt(a[1]);
 
 
            // Consume the newline character
            //reader.readLine();
 
            // Initialize arrays
            adjList = new ArrayList<>();
            visited = new boolean[n+1];
            color = new boolean[n+1];
            for (int i = 0; i < n + 1; i++) {
                adjList.add(new ArrayList<>());
            }
 
            // Read edge information
            for (int i = 0; i < m; i++) {
                 s =reader.readLine();
                a=s.split(" ");
                int a1=Integer.parseInt(a[0]);
                int a2=Integer.parseInt(a[1]);
                adjList.get(a1).add(a2);
                adjList.get(a2).add(a1);
            }
        //bfs
        for(int i=1;i<=n;i++)
        {
            if(!visited[i])
                dfs(i,true);
        }
        String output = "";
        for(int i=1;i<n+1;i++)
        {
            output+=color[i]?"1 ":"2 ";
 
        }
        System.out.print(output);
 
                // Don't forget to close scanner and output stream
//        reader.close();
        System.out.close();
    }

    public static void dfs(Integer node, boolean clr) // color this node with clr
    {
        visited[node]=true;
        color[node]=clr;
        boolean nextColor = !clr;
        for(Integer child:adjList.get(node)){
 
            if(!visited[child]){
                dfs(child,nextColor);
            }else {
                if (color[node] == color[child]) {
                    System.out.println("IMPOSSIBLE");
                    System.exit(0);
                }
            }
        }
    }
 
 
Leave a Comment