1466.cpp (863B)
1 class Solution { 2 public: 3 int minReorder(int n, vector<vector<int>> &connections) { 4 unordered_set<string> us; 5 vector<bool> visited(n, false); 6 vector<vector<int>> adj(n, vector<int>()); 7 8 for (auto &e : connections) { 9 us.insert(to_string(e[0]) + " " + to_string(e[1])); 10 adj[e[0]].push_back(e[1]); 11 adj[e[1]].push_back(e[0]); 12 } 13 14 int res = 0; 15 16 stack<int> st; 17 st.push(0); 18 visited[0] = true; 19 while (!st.empty()) { 20 int root = st.top(); 21 st.pop(); 22 for (auto c : adj[root]) 23 if (!visited[c]) { 24 if (!us.count(to_string(c) + " " + to_string(root))) res++; 25 visited[c] = true; 26 st.push(c); 27 } 28 } 29 return res; 30 } 31 };