Topological Sorting

Question:

http://www.lintcode.com/en/problem/topological-sorting/
Given an directed graph, a topological order of the graph nodes is defined as follow:
For each directed edge A -> B in graph, A must before B in the order list.
The first node in the order can be any node in the graph with no nodes direct to it.
Find any topological order for the given graph.

Answer:
class Solution {
public:
    /*
     * @param ratings: Children's ratings
     * @return: the minimum candies you must give
     */
    int candy(vector<int> &ratings) {
        // write your code here
        vector<int> candys(ratings.size(), 1);
        for (int i = 0; i < ratings.size() - 1; i++) {
            if (ratings[i+1] > ratings[i])
                candys[i+1] = candys[i] + 1;
        }
        for (int i = ratings.size() - 1; i > 0; i--) {
            if (ratings[i-1] > ratings[i])
                candys[i-1] = max(candys[i] + 1, candys[i-1]);
        }
        int count = 0;
        for (auto i : candys)
            count += i;
        return count;
    }
};

Comments

Popular posts from this blog

How to fix error : no module named sendgrid when try to use sendgrid python lib in PHP.

react-native run-android : sun.security.provider.cert path.SunCertPathBuilderException : unable to find valid certification path to req uested target

react-native run-android : do not build/update modified code(App.js)