1466. Reorder Routes to Make All Paths Lead to the City Zero

 

https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/submissions/

There are n cities numbered from 0 to n-1 and n-1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.

Roads are represented by connections where connections[i] = [a, b] represents a road from city a to b.

This year, there will be a big event in the capital (city 0), and many people want to travel to this city.

Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.

It's guaranteed that each city can reach the city 0 after reorder.

Example 1:

Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
Output: 3
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).

Example 2:

Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
Output: 2
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).

Example 3:

Input: n = 3, connections = [[1,0],[2,0]]
Output: 0

Constraints:

  • 2 <= n <= 5 * 10^4
  • connections.length == n-1
  • connections[i].length == 2
  • 0 <= connections[i][0], connections[i][1] <= n-1
  • connections[i][0] != connections[i][1]

算法思路:

  • dfs
  • sort and serch with set
  • bfs

方法1:已经减支不少,但还是超时,需要配合使用其他数据结构才可以通过

//TLE
//68 / 72 test cases passed.
class Solution {
public:
    int minReorder(int n, vector<vector<int>>& connections) {
        int res = 0;
        vector<bool> visited(n, false);
        dfs(connections, visited, 0, res);
        return res;
    }
private:
    void dfs(vector<vector<int>>& connections, vector<bool>& visited, int v, int& res) {
        if (visited[v]) return;
        visited[v] = true;
        
        for (int i = 0; i < connections.size(); i++) {
            if (connections[i][0] == v && !visited[connections[i][1]]) {
                res++;
                dfs(connections, visited, connections[i][1], res);
            } else if (connections[i][1] == v && !visited[connections[i][0]]) {
                dfs(connections, visited, connections[i][0] , res);
            }
        }
    }
};

方法2: 

//ac: 41.62%
class Solution {
public:
    int minReorder(int n, vector<vector<int>>& connections) {
        sort(connections.begin(), connections.end(), [=](vector<int>& v1, vector<int>& v2){
            if (v1[0] < v2[0]) return true;
            else if (v1[0] == v2[0] && v1[1] < v2[1]) return true;
            return false;
        });
        
        set<int> myset;
        for (int i = 1; i < n; i++) myset.insert(i);
        
        int res = 0;
        int u, v;
        for (auto vec : connections) {
            u = vec[0];
            v = vec[1];
            
            if (u == 0) {
                res++;
                myset.erase(v);
            } else if (myset.find(u) == myset.end()) {
                res++;
                myset.erase(v);
            } else if (myset.find(v) == myset.end()) {
                myset.erase(u);
            }
        }
        return res;
    }
};
//ac: 62.95%
//Runtime: 660 ms
class Solution {
public:
    int minReorder(int n, vector<vector<int>>& connections) {
        sort(connections.begin(), connections.end(), [=](vector<int>& v1, vector<int>& v2){
            if (v1[0] < v2[0]) return true;
            else if (v1[0] == v2[0] && v1[1] < v2[1]) return true;
            return false;
        });
        
        unordered_set<int> myset;
        for (int i = 1; i < n; i++) myset.insert(i);
        
        int res = 0;
        int u, v;
        for (auto vec : connections) {
            u = vec[0];
            v = vec[1];
            
            if (myset.find(u) == myset.end()) {
                res++;
                myset.erase(v);
            } else if (myset.find(v) == myset.end()) {
                myset.erase(u);
            }
        }
        return res;
    }
};

方法3:

//ac: 86.10%
//Runtime: 520 ms
class Solution {
public:
  int minReorder(int n, vector<vector<int>>& connections) {
    vector<vector<pair<int, int>>> g(n); // u -> {v, cost}
    for (const auto& e : connections) {  // u -> v is an edge of original connections
      g[e[0]].emplace_back(e[1], 1);     // u -> v, needs flip
      g[e[1]].emplace_back(e[0], 0);     // v -> u, no cost
    }
    int res = 0;
    queue<int> q{{0}};  // start from city 0
    vector<bool> visited(n, false);
    while (!q.empty()) {
      int u = q.front(); q.pop();
      visited[u] = true;
      for (const auto& [v, cost] : g[u]) {
        if (visited[v]) continue;
        res += cost;
        q.push(v);
      }
    }
    return res;
  }
};

参考资料:

https://blog.csdn.net/u013325815/article/details/106454528 (代码有小错误,wa,需要小修改,ac代码见第2,3段代码)

https://zxi.mytechroad.com/blog/graph/leetcode-1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero/

https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/661710/Simple-Explanation-or-DFS-with-edge-deletion-or-Idea-or-Code-or-Comments-or-Q-and-A

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值