标签:style http color os io for ar div amp
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
What is the minimum candies you must give?
题目说N个孩子排成一行,每个孩子被赋予一个rating,要求给candy给孩子满足每个孩子都至少有一个candy同时拥有更高rating
的孩子比他的邻居有更多的candy。
思路1:转为有向图,用拓扑排序。
拓扑排序用到了每个节点的入度(有多少个节点指向该节点)、从该节点出发直接到达的节点。
步骤:
class Solution { public: int candy(vector<int> &ratings) { size_t len = ratings.size(); if (len == 1) { return 1; } vector<int> ins(len, 0); vector<vector<int> > outs(len, vector<int>()); for (int i = 0; i < len; ++i) { if (i - 1 >= 0 && ratings[i - 1] > ratings[i]) { ++ins[i - 1]; outs[i].push_back(i - 1); } if (i + 1 < len && ratings[i + 1] > ratings[i]) { ++ins[i + 1]; outs[i].push_back(i + 1); } } queue<pair<int, int> > q; for (int i = 0; i < len; ++i) { if (!ins[i]) { q.push(make_pair(i, 1)); } } int ans = 0; while (!q.empty()) { pair<int, int> front = q.front(); q.pop(); ans += front.second; for (int i = 0; i < outs[front.first].size(); ++i) { --ins[outs[front.first][i]]; if (!ins[outs[front.first][i]]) { q.push(make_pair(outs[front.first][i], front.second + 1)); } } } return ans; } };
class Solution { public: int candy(vector<int> &ratings) { size_t len = ratings.size(); if (len == 1) { return 1; } vector<int> candy_num(len, 0); int ans = 0; for (size_t i = 0; i < len; ++i) { ans += get_candy_num(candy_num, i, len, ratings); } return ans; } private: int get_candy_num(vector<int> &candy_num, size_t k, size_t len, vector<int> &ratings) { if (candy_num[k]) return candy_num[k]; if (k == 0) { if (ratings[k + 1] >= ratings[k]) { return candy_num[k] = 1; } else { return candy_num[k] = get_candy_num(candy_num, k + 1, len, ratings) + 1; } } else if (k == len - 1) { if (ratings[k - 1] >= ratings[k]) { return candy_num[k] = 1; } else { return candy_num[k] = get_candy_num(candy_num, k - 1, len, ratings) + 1; } } else { if (ratings[k - 1] >= ratings[k] && ratings[k + 1] >= ratings[k]) { return candy_num[k] = 1; } else if (ratings[k] > ratings[k - 1] && ratings[k] > ratings[k + 1]) { int left = get_candy_num(candy_num, k - 1, len, ratings); int right = get_candy_num(candy_num, k + 1, len, ratings); left < right ? candy_num[k] = right + 1 : candy_num[k] = left + 1; return candy_num[k]; } else if (ratings[k] > ratings[k - 1]) { return candy_num[k] = get_candy_num(candy_num, k - 1, len, ratings) + 1; } else if (ratings[k] > ratings[k + 1]) { return candy_num[k] = get_candy_num(candy_num, k + 1, len, ratings) + 1; } } return 1; } };
标签:style http color os io for ar div amp
原文地址:http://blog.csdn.net/freeliao/article/details/38796747