Edge Weight Assignment

D - Edge Weight Assignment

Reference: Codeforces Round # 633 Editorial

I feel that the key to this question is that the graph should be transformed into a tree, so that the logic will be much clearer.

If there is an odd number (not 1) between the leaves, then the smallest f value must be 3, otherwise it is 1. It can be obtained by solving the distance from other leaf nodes to a certain leaf node, and the conclusion is valid for any node (that is, if the node is satisfied, then the other nodes are also satisfied).

Another very important conclusion is that if there is a situation where a parent node connects two leaf nodes, then the maximum value of f needs to be reduced by 1, because the value of the leaf node has been determined, there can be no other changes.

// Created by CAD on 2020/4/13.
#include <bits/stdc++.h>
using namespace std;

const int maxn=1e5+5;
vector<int> e[maxn];
bool bj=0;
void dfs(int u,int fa=0,int x=0){
    for(auto i:e[u])
        if(i!=fa) dfs(i,u,x^1);
    if(e[u].size()==1&&x) bj=1;
}
int vis[maxn];
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
//    FOPEN;
    int n;cin>>n;
    for(int i=1,x,y;i<=n-1;++i)
        cin>>x>>y,e[x].push_back(y),e[y].push_back(x);
    for(int i=1;i<=n;++i)
        if(e[i].size()==1){
            dfs(i);break;
        }
    int ans=n-1;
    for(int i=1;i<=n;++i)
        if(e[i].size()==1)
            ans-=vis[e[i][0]],vis[e[i][0]]=1;
    cout<<(bj?3:1)<<" "<<ans<<"\n";
    return 0;
}

Guess you like

Origin www.cnblogs.com/CADCADCAD/p/12694311.html