dfs and similar dp graphs trees *1700

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;

void findMinReversals(vector<vector<pair<int, int>>> &adjList, vector<bool> &visited, int src, int level, int &rootAns, int &minRes, int oneCount, vector<int> &minNodes){

    visited[src] = true;
    int val = level-2*oneCount;
    if(val < minRes){
        minRes = val;
        minNodes.clear();
        minNodes.push_back(src);
    }
    else if(val == minRes){
        minNodes.push_back(src);
    }

    for(auto p: adjList[src]){
        if(!visited[p.first]){
            rootAns += p.second;
            findMinReversals(adjList, visited, p.first, level+1, rootAns, minRes, oneCount + p.second, minNodes);
        }
    }
}

int main(){


    int n;
    cin >> n;

    vector<vector<pair<int, int>>> adjList(n+1);
    
    for(int i = 1; i <= n-1; i++){
        int u, v;

        cin >> u >> v;

        adjList[u].push_back({v, 0});
        adjList[v].push_back({u, 1});
    }

    vector<bool> visited(n+1, false);
    int minRes = INT_MAX;
    vector<int> minNodes;
    int rootAns = 0;
    findMinReversals(adjList, visited, 1, 0, rootAns, minRes, 0, minNodes);
    sort(minNodes.begin(), minNodes.end());

    cout << rootAns + minRes << endl;

    for(int node: minNodes){
        cout << node << " ";
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

1711A - Perfect Permutation
1701B - Permutation
1692A - Marathon
1066A - Vova and Train
169B - Replacing Digits
171D - Broken checker
380C - Sereja and Brackets
1281B - Azamon Web Services
1702A - Round Down the Price
1681C - Double Sort
12A - Super Agent
1709A - Three Doors
1680C - Binary String
1684B - Z mod X = C
1003A - Polycarp's Pockets
1691B - Shoe Shuffling
1706A - Another String Minimization Problem
1695B - Circle Game
1702B - Polycarp Writes a String from Memory
1701A - Grass Field
489C - Given Length and Sum of Digits
886B - Vlad and Cafes
915A - Garden
356A - Knight Tournament
1330A - Dreamoon and Ranking Collection
1692B - All Distinct
1156C - Match Points
1675A - Food for Animals
1328C - Ternary XOR
1689A - Lex String