Source Code
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
#define all(v) v.begin(), v.end()
#define pb push_back    
#define sz(x) (int)(x).size()
const int N = 1e5 + 5;
void solve() {
    
    int n;
    cin >> n;
    map<char, int> m;
    m['U'] = 0;
    m['D'] = 1;
    m['L'] = 2;
    m['R'] = 3;
    vector<vi> deg(n + 10, vi(4));
    vi can(n + 5, 1), bad(n + 5, 0);
    vector<vector<pii>> g(n + 5);
    
    for(int i = 0; i < n - 1; ++i){
        int u, v;
        char c;
        cin >> u >> v >> c;
        g[u].pb({v, c});
        g[v].pb({u, c});
        ++deg[u][m[c]];
        ++deg[v][m[c]];
        if(deg[u][m[c]] >= 2)   
            can[u] = 0;
        if(deg[v][m[c]] >= 2)   
            can[v] = 0;
    }
    
    function<void(int, int, int, bool)> dfs = [&](int u, int d, int p, bool s) {
        if(p != -1) {
            // if(u == 6)
            //     cout << "Hi\n";
            bad[u] = 1;
        }
        for(auto [v, c] : g[u]){
            if(v == p || bad[v])
                continue;
            int j = m[c];
            if(p == -1){
                if(d != j && !s)
                    dfs(v, c, u, s);
                else if(s && d == j)
                    dfs(v, c, u, s);
            }else{
                dfs(v, c, u, s);
            }
        } 
    };

    for(int i = 1; i <= n; ++i){
        if(bad[i]) continue;
        for(int j = 0; j < 4; ++j){
            if(deg[i][j] >= 2){
                // bad[i] = 1;
                dfs(i, j, -1, 0);
            }
        }
        for(int j : {0, 2}){
            if(deg[i][j] && deg[i][j + 1])
                dfs(i, j, -1, 1), dfs(i, j + 1, -1, 1);
        }
    }
    
    vi ans;
    for(int i = 1; i <= n; ++i){
        if(!bad[i] && can[i]) 
            ans.pb(i);
    }
    
    for(int x : ans)
        cout << x << ' ';
        
}
int main() {
    // cin.tie(0)->sync_with_stdio(0);
    int t = 1;
    cin >> t;
    // scanf("%d",&t);
    while(t--)
        solve(), cout << '\n';
}
Copy
Flow Sources I noomaK
GNU G++17
978 ms
27.1 MB
Accepted