Find most frequent value of ancestors for each Node of given Tree
#include <bits/stdc++.h>
using
namespace
std;
unordered_map<
int
,
int
> ans;
unordered_map<
int
,
int
> freq;
set<pair<
int
,
int
> > s;
void
addEdge(vector<
int
> adj[],
int
u,
int
v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void
helper(
int
v,
int
flag)
{
if
(s.find({ freq[v], v }) != s.end())
s.erase(s.find({ freq[v], v }));
freq[v] += flag;
s.insert({ freq[v], v });
}
void
ModeOfAncestors(vector<
int
> adj[],
int
node,
vector<
int
>& vis, vector<
int
>& val)
{
int
v = val[node];
helper(v, 1);
ans[node] = (*(--s.end())).second;
vis[node] = 1;
for
(
auto
child : adj[node]) {
if
(vis[child] == 0)
ModeOfAncestors(adj, child, vis, val);
}
helper(v, -1);
}
int
main()
{
int
N = 9;
vector<
int
> adj[N];
addEdge(adj, 0, 1);
addEdge(adj, 0, 2);
addEdge(adj, 1, 3);
addEdge(adj, 1, 4);
addEdge(adj, 1, 5);
addEdge(adj, 2, 6);
addEdge(adj, 2, 7);
addEdge(adj, 2, 8);
vector<
int
> val = { 5, 2, 3, 2, 5, 1, 3, 5, 1 };
vector<
int
> vis(N, 0);
ModeOfAncestors(adj, 0, vis, val);
for
(
int
i = 0; i < N; i++)
cout << ans[i] <<
" "
;
cout << endl;
return
0;
}
#include <bits/stdc++.h>
using
namespace
std;
unordered_map<
int
,
int
> ans;
unordered_map<
int
,
int
> freq;
set<pair<
int
,
int
> > s;
void
addEdge(vector<
int
> adj[],
int
u,
int
v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void
helper(
int
v,
int
flag)
{
if
(s.find({ freq[v], v }) != s.end())
s.erase(s.find({ freq[v], v }));
freq[v] += flag;
s.insert({ freq[v], v });
}
void
ModeOfAncestors(vector<
int
> adj[],
int
node,
vector<
int
>& vis, vector<
int
>& val)
{
int
v = val[node];
helper(v, 1);
ans[node] = (*(--s.end())).second;
vis[node] = 1;
for
(
auto
child : adj[node]) {
if
(vis[child] == 0)
ModeOfAncestors(adj, child, vis, val);
}
helper(v, -1);
}
int
main()
{
int
N = 9;
vector<
int
> adj[N];
addEdge(adj, 0, 1);
addEdge(adj, 0, 2);
addEdge(adj, 1, 3);
addEdge(adj, 1, 4);
addEdge(adj, 1, 5);
addEdge(adj, 2, 6);
addEdge(adj, 2, 7);
addEdge(adj, 2, 8);
vector<
int
> val = { 5, 2, 3, 2, 5, 1, 3, 5, 1 };
vector<
int
> vis(N, 0);
ModeOfAncestors(adj, 0, vis, val);
for
(
int
i = 0; i < N; i++)
cout << ans[i] <<
" "
;
cout << endl;
return
0;
}