using
System;
using
System.Collections.Generic;
public
class
GFG
{
static
void
findNodesinCycle(
int
u,
bool
[] vis,
int
[] prev,
List<List<
int
>> adj,List<
int
> inCycle)
{
vis[u] =
true
;
foreach
(
int
v
in
adj[u])
{
if
(!vis[v])
{
prev[v] = u;
findNodesinCycle(v, vis, prev,adj, inCycle);
if
(inCycle.Count > 0)
return
;
}
else
if
(v != prev[u])
{
int
curr = u;
inCycle.Add(curr);
while
(curr != v)
{
curr = prev[curr];
inCycle.Add(curr);
}
return
;
}
}
}
static
int
sumOfnonCycleNodes(
int
u, List<List<
int
>> adj,List<
int
> inCycle,
bool
[] vis,
int
[] arr)
{
vis[u] =
true
;
int
sum = 0;
foreach
(
int
v
in
adj[u])
{
if
(!vis[v] && !inCycle.Contains(v))
{
sum += (arr[v - 1] + sumOfnonCycleNodes(v, adj, inCycle, vis, arr));
}
}
return
sum;
}
static
bool
isBreakingPossible(List<List<
int
>> adj,
int
[] arr,
int
N)
{
List<
int
> inCycle =
new
List<
int
>();
bool
[] vis =
new
bool
[N + 1];
int
[] prev =
new
int
[N + 1];
findNodesinCycle(1, vis, prev, adj, inCycle);
foreach
(
int
u
in
inCycle)
{
arr[u - 1] += sumOfnonCycleNodes(u, adj, inCycle, vis, arr);
}
int
tot_sum = 0;
foreach
(
int
node
in
inCycle)
{
tot_sum += arr[node - 1];
}
if
(tot_sum % 2 != 0)
return
false
;
int
req_sum = tot_sum / 2;
Dictionary<
int
,
int
> map =
new
Dictionary<
int
,
int
>();
map.Add(0, -1);
int
curr_sum = 0;
for
(
int
i = 0; i < inCycle.Count; i++)
{
curr_sum += arr[inCycle[i] - 1];
if
(map.ContainsKey(curr_sum - req_sum))
{
return
true
;
}
map.Add(curr_sum, i);
}
return
false
;
}
static
void
checkCycleDivided(
int
[,] edges,
int
[] arr,
int
N)
{
List<List<
int
>> adj =
new
List<List<
int
>>();
for
(
int
i = 0; i <= N; i++)
{
adj.Add(
new
List<
int
>());
}
for
(
int
i = 0; i < N; i++)
{
int
u = edges[i,0];
int
v = edges[i,1];
adj[u].Add(v);
adj[v].Add(u);
}
Console.Write(isBreakingPossible(adj, arr, N) ?
"Yes"
:
"No"
);
}
static
public
void
Main (){
int
N = 10;
int
[,] edges = { { 1, 2 }, { 1, 5 },
{ 1, 3 }, { 2, 6 },
{ 2, 7 }, { 2, 4 },
{ 4, 8 }, { 4, 3 },
{ 3, 9 }, { 9, 10 } };
int
[] arr = { 4, 2, 3, 3, 1,
2, 6, 2, 2, 5 };
checkCycleDivided(edges, arr, N);
}
}