File tree Expand file tree Collapse file tree 1 file changed +75
-0
lines changed
Expand file tree Collapse file tree 1 file changed +75
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.io.* ;
3+ import java.util.* ;
4+
5+ public class Main {
6+
7+ static ArrayList<Integer > [] graph;
8+ static int [] color;
9+ static int v, e;
10+
11+ public static void main (String [] args ) throws Exception {
12+ BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
13+ StringTokenizer st;
14+ StringBuilder sb = new StringBuilder ();
15+ int T = Integer . parseInt(br. readLine());
16+
17+ for (int t = 0 ; t < T ; t++ ) {
18+ st = new StringTokenizer (br. readLine());
19+ v = Integer . parseInt(st. nextToken());
20+ e = Integer . parseInt(st. nextToken());
21+
22+ graph = new ArrayList [v + 1 ];
23+ for (int i = 1 ; i <= v; i++ ) graph[i] = new ArrayList<> ();
24+
25+ for (int i = 0 ; i < e; i++ ) {
26+ st = new StringTokenizer (br. readLine());
27+ int a = Integer . parseInt(st. nextToken());
28+ int b = Integer . parseInt(st. nextToken());
29+ graph[a]. add(b);
30+ graph[b]. add(a);
31+ }
32+
33+ color = new int [v + 1 ];
34+ boolean ok = true ;
35+
36+ for (int i = 1 ; i <= v && ok; i++ ) {
37+ if (color[i] == 0 ) {
38+ ok = bfs(i);
39+ }
40+ }
41+
42+ if (ok){
43+ sb. append(" YES\n " );
44+ }
45+ else {
46+ sb. append(" NO\n " );
47+ }
48+ }
49+
50+ System . out. print(sb. toString());
51+ }
52+
53+ static boolean bfs (int s ) {
54+ ArrayDeque<Integer > q = new ArrayDeque<> ();
55+ color[s] = 1 ;
56+ q. offer(s);
57+
58+ while (! q. isEmpty()) {
59+ int u = q. poll();
60+ int nextColor = - color[u];
61+
62+ for (int v : graph[u]) {
63+ if (color[v] == 0 ) {
64+ color[v] = nextColor;
65+ q. offer(v);
66+ } else if (color[v] == color[u]) {
67+ return false ;
68+ }
69+ }
70+ }
71+ return true ;
72+ }
73+ }
74+
75+ ```
You can’t perform that action at this time.
0 commit comments