-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUva11369.java
More file actions
114 lines (101 loc) · 2.36 KB
/
Copy pathUva11369.java
File metadata and controls
114 lines (101 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import java.util.* ;
import java.io.* ;
/*
* Uva 11396 - Claw Decomposition
* @ author Mostafa Kamel
*/
public class Uva11369
{
public static void main(String[] args)throws IOException
{
Scanner sc = new Scanner(System.in);
PrintWriter pr = new PrintWriter(System.out);
while(sc.hasNext())
{
int n = sc.nextInt();
if(n==0)
break;
Graph G = new Graph(n+1);
int u = sc.nextInt();
int v = sc.nextInt();
while(u!= 0 && v != 0)
{
G.addEdge(u,v);
u = sc.nextInt();
v = sc.nextInt();
}
pr.println(new TwoColor(G).isBipartite() ? "YES" : "NO");
}
pr.close();
sc.close();
}
}
class Graph
{
private final int V ;
private int E ;
private ArrayList<Integer>[] adj ;
public Graph(int V)
{
this.V = V ;
adj = (ArrayList<Integer>[])new ArrayList[V];
for (int i = 0; i < V ; i++)
adj[i] = new ArrayList<Integer>();
}
public int V(){ return V; }
public int E(){ return E; }
public void addEdge(int v , int w)
{
adj[v].add(w);
adj[w].add(v);
E++ ;
}
public Iterable<Integer> adj(int v)
{ return adj[v]; }
@Override
public String toString()
{
String s = V + " vertices, " + E + " edges\n";
for (int v = 0; v < V ; v++)
{
s += v + ": " ;
for(int w : adj(v))
s += w + " ";
s += "\n";
}
return s ;
}
}
class TwoColor
{
private boolean[]marked ;
private boolean[]color ;
private boolean isTwoColorable = true ;
public TwoColor(Graph G)
{
marked = new boolean[G.V()];
color = new boolean[G.V()];
for (int s = 0; s < G.V(); s++) {
if (!marked[s])
dfs(G,s);
}
}
private void dfs(Graph G , int v)
{
marked[v] = true ;
for(int w : G.adj(v))
if(!marked[w])
{
color[w] = !color[v];
dfs(G,w);
}
else if(color[w]==color[v])
{
isTwoColorable = false ;
}
}
public boolean isBipartite()
{
return isTwoColorable ;
}
}