Please subscribe to the official Codeforces channel in Telegram via the link https://t.me/codeforces_official. ×

### qwerty29's blog

By qwerty29, history, 4 years ago, You are given a tree consisting of n nodes.
A matching is a set of edges where each node is an endpoint of at most one edge. What is the maximum number of edges in a matching?

My Approach:
1) Run BFS to find the bipartite partition for the given tree.
2) We iterate over the number of nodes in the maximum of the above sets.
3) Since every node in this set will have a corresponding node in the other set we can choose this node edge in our answer.
4) while taking the nodes in this set we have to make sure that its neighboring node is only visited once i.e. other nodes in this set cannot share a node in the other set.

#include <bits/stdc++.h>
#define all(v) (v).begin(),(v).end()
using namespace std;

int main(){
ios_base::sync_with_stdio(false); cin.tie(NULL);
int n; cin >> n;
vector<vector<int> > graph(n+1);

for(int i=0;i<n-1;++i){
int a,b; cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}

queue<int> q;
vector<int> color(n+1);
vector<int> visited(n+1,0);

q.push(1);
color = 0;
visited = 1;
while(!q.empty()){
int node = q.front(); q.pop();
for(int i:graph[node]){
if(!visited[i]){
visited[i] = 1;
color[i] = (color[node]+1)%2;
q.push(i);
}
}
}
vector<int> first;
vector<int> second;
for(int i=1;i<=n;++i){
if(color[i]==0) first.push_back(i);
else second.push_back(i);
}
int count = 0;
fill(all(visited),0);
if(first.size() < second.size()) swap(first,second);
for(int i=0;i<first.size();++i) {
visited[first[i]] = 1;
for(int it:graph[first[i]]){
if(!visited[it]){
visited[it] = 1;
count++;
break;
}
}
}
cout << count << '\n';
return 0;
}


Am I going in the right direction for this problem since I am new to this concept?
Thank you!.  Comments (14)
| Write comment?
 » It would be great if someone could help out to get solution for this problem
 » 4 years ago, # | ← Rev. 2 →   This problem is best solved with DP. First, you should choose a node as a root for the given tree. For the sake of simplicity, you may choose node 1 as your root. Then calculate the following dp[node][taken] = the maximum number of matches you can obtain in the subtree with root node, where taken is 1 if you included node in a matching, 0 if not. The recurrence is:dp[node] = sum(max(dp[son], dp[son])) where son is a direct son of nodedp[node] = max(1 + dp[son] + sum(max(dp[son2], dp[son2])) where son2 is a son of node, and son2 != son) where son is a son of node.Feel free to ask me if you have further questions on this.
•  » » thank you! very helpful
•  » » @popabogdannnn can you show your code? My implementation failed based on your idea.
•  » » dp[node] = sum( dp[son] ) also works. Why is this greedy decision working?
•  » » » You might have got it now but for finding dp[node], we are not considering the current node in any matching edge. Thus we can greedily pick the best from all nodes. That is dp[son]
•  » » 3 years ago, # ^ | ← Rev. 3 →   Yeah but this particular question can also be solved using a greedy approach. Just perform a postorder traversal i.e start with the leaf edges and go up to the root of the tree(whatever we choose it to be). I mean DP is good as we don't have to think much that whether it can be solved using greedy or not but if we carefully observe it can be solved using greedy. This is my solution please tell me if there will be some cases that will give WA as it passed on CSES.ll n,cnt; vector g; vector visited;void dfs(ll src,ll par){ for(auto nbr:g[src]){ if(nbr != par) dfs(nbr,src); } // cout<>n; g = vector>(n + 1); visited = vector(n + 1,false); cnt = 0; rep(i,n - 1){ ll u,v; cin>>u>>v; g[u].pb(v); g[v].pb(u); } dfs(1,0); cout<
•  » » » How this is passing, it is totally a wrong solution!
•  » » » » Why do you think that this approach is wrong? Tell me if I am wrong: My convention: By colouring a node I mean one of the edges contain that node and the node is not left alone. Now, there are two possibilities: 1. Colour a node 2. Uncoloured 1. Coloured: If we have to colour a particular node x, then why should we choose some other neighbour of x which is not a leaf node as a non-leaf node will disturb other nodes as well. In this case, if there is an edge to a leaf then we must take it. 2. Uncoloured: If a node x is uncoloured and it has one leaf node as its neighbour then we can take one more edge, i.e, an edge between the leaf node and node x. It will not disturb other nodes. It is similar to topological ordering, where we take nodes having indegrees 0 first, then subtract the indegrees of all its neighbours by 1, if any of them becomes 0 then push it into the queue and continue. My code (Similar logic, implementation similar to Kahn's algorithm) : https://cses.fi/paste/052f635c07bfa51c26f96a/
•  » » 5 months ago, # ^ | ← Rev. 2 →   Codevoid dfs(ll s,ll p,vvl& g,vvl& ans){ ll sum=0; for(auto ch:g[s]){ if(ch==p)continue; dfs(ch,s,g,ans); sum+=max(ans[ch],ans[ch]); } ans[s]=sum; for(auto ch:g[s]){ if(ch==p)continue; ans[s]=max(ans[s],1+ans[ch]+(sum-max(ans[ch],ans[ch]))); } } void chal(){ ll n; cin>>n; vvl g(n+1); vvl ans(n+1,vl(2)); fo(i,n-1){ ll u,v; cin>>u>>v; g[u].pb(v); g[v].pb(u); } dfs(1,0,g,ans); ll fans=0; Fo(i,1,n+1){ fans=max(fans,max(ans[i],ans[i])); } cout<
 » 4 years ago, # | ← Rev. 2 →   You are not going in right direction. You need to use a maximum matching algorithm like hopkraft_karp. Your algo will fail in cases like this: 4 1 3 1 4 2 3if you algo chooses 1 3Here is my solution using Hopkraft_karp Code Maximum Matching#include using namespace std; // #define int long long int #define vec vector #define pb push_back #define s(x) scanf("%d",&x) #define all(x) x.begin(),x.end() #define pii pair #define fi first #define se second #define mod 1000000007 #define SZ 400005 #define endl "\n" #define trace(x) cerr << #x << ": " << x << endl #define boost ios::sync_with_stdio(0);cin.tie(0) int x, u, v; vec adj_inp; ///////////////////////////////////////////////// #define NIL 0 #define INF (1<<28) vector< int > adj[SZ]; int n, m, match[SZ], dist[SZ]; // n: number of nodes on left side, nodes are numbered 1 to n // m: number of nodes on right side, nodes are numbered n+1 to n+m // adj = NIL ∪ adj1[adj[1---n]] ∪ adj2[adj[n+1---n+m]] bool bfs() { int i, u, v, len; queue Q; for(i=1; i<=n; i++) { if(match[i]==NIL) { dist[i] = 0; Q.push(i); } else dist[i] = INF; } dist[NIL] = INF; while(!Q.empty()) { u = Q.front(); Q.pop(); if(u!=NIL) { for(int v: adj[u]) { if(dist[match[v]]==INF) { dist[match[v]] = dist[u] + 1; Q.push(match[v]); } } } } return (dist[NIL]!=INF); } bool dfs(int u) { int i, v, len; if(u!=NIL) { for(int v: adj[u]) { if(dist[match[v]]==dist[u]+1) { if(dfs(match[v])) { match[v] = u; match[u] = v; return true; } } } dist[u] = INF; return false; } return true; } int hopcroft_karp_max_match() { int matching = 0, i; // match[] is assumed NIL for all vertex in adj while(bfs()) for(i=1; i<=n; i++) if(match[i]==NIL && dfs(i)) matching++; return matching; } void print_matching() { for(int i = 1; i <=n ; i++) { if(match[i] != NIL) cout << i << " " << match[i]-n << endl; } } void make_bipartite_dfs(int u, int p, int l) { if(l%2 and p != -1) { adj[u].pb(p+n); adj[p+n].pb(u); } for(int v: adj_inp[u]) { if(v!=p) { if(l%2) { adj[u].pb(v+n); adj[v+n].pb(u); } make_bipartite_dfs(v, u, l+1); } } } void purple() { cin >> n; for(int i = 0; i < n-1; i++) { cin >> u >> v; adj_inp[u].pb(v); adj_inp[v].pb(u); } make_bipartite_dfs(1, -1, 1); cout << hopcroft_karp_max_match() << endl; } signed main() { boost; int t=1; while(t--) purple(); } 
 » This is a nice problem, I've solved it before. Root the tree at an arbitrary node. Idea is to store $2$ arrays: $take[n]$ and $leave[n]$. Here $take[u]$ stores the number of edges you can take up into a matching of the subtree rooted at $u$, given that $u$ is present in the matching. $leave[u]$ is similarily defined, except that you do not take $u$. Now the transitions are simple. See my code for details: https://cses.fi/paste/7b6250d2bd69c63f20d838/
 » Can I not directly say that the cardinality of smaller of the two bipartite partitions will be the answer?
 » why everyone overkilling this simple problem ? code