Leetcode. 135 Candy(Hard)
来源:互联网 发布:java防止表单重复提交 编辑:程序博客网 时间:2024/05/29 18:54
**Problem**
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:
1.Each child must have at least one candy.
2.Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
**Example**
Input: [0]
Output: 1
**Algorithm**
本题题意为n个小朋友排成一行,每个小朋友拥有一个等级,给每个小朋友分发糖果,要求:
1.每个小朋友都至少有一颗糖;
2.相邻两个小朋友中等级较高者要比较低者拥有更多的糖果。
求最少需要多少糖果。
本题可采用拓扑排序的思想进行求解。我们先建立有向图:每个小朋友视为顶点,对于每对相邻的小朋友,从等级低的小朋友发出一条边指向等级高的小朋友。记录每个点的度数。然后,将度数为0的点放进队列,更新糖果总数。每次从队列中取出一个点,将该点所指向的点的度数-1,若生成新的度数为0的点,放进队列,更新糖果总数。重复上述过程,即可得到最终糖果数。
建图的时间为O(n),拓扑排序的时间为O(n),所以总的时间复杂度为O(n+n)=O(n)
**Code**
#include<iostream>#include<vector>#include<queue>using namespace std;class Solution {public: int candy(vector<int>& ratings) { int num = ratings.size(); vector<vector<int> > dag(num); vector<int> dig(num); vector<int> can(num, 1); for(int i = 1; i < num; ++i){ if(ratings[i] < ratings[i-1]){ dag[i].push_back(i-1); dig[i-1]++; } else if(ratings[i] > ratings[i-1]){ dag[i-1].push_back(i); dig[i]++; } } int ans = 0; queue<int> q; for(int i = 0; i < num; ++i){ if(dig[i] == 0){ q.push(i); ans += can[i]; } } while(q.size()){ int temp = q.front(); q.pop(); for(int i=0;i<dag[temp].size();++i){ int cn = dag[temp][i]; dig[cn]--; can[cn] = max(can[cn], can[temp] + 1); if(dig[cn] == 0) { q.push(cn); ans += can[cn]; } } } return ans; }};
0 0
- [Leetcode 135, Hard] Candy
- Leetcode. 135 Candy(Hard)
- 【leetcode】 Candy (hard,pick one)
- 第十一周 leetcode 135. Candy(Hard)
- 【LeetCode】135.Candy(hard)解题报告
- leetcode hard模式专杀之135. Candy
- LeetCode: Candy [135]
- [leetcode 135] Candy
- LeetCode(135) Candy
- [LeetCode 135]Candy
- LeetCode 135 Candy
- leetcode || 135、Candy
- [leetcode-135]Candy(java)
- leetcode 135: Candy
- leetCode #135 Candy
- 【LeetCode-135】Candy
- Leetcode (135) Candy
- LeetCode(135)Candy
- 认识html标签
- Atitit 发帖机实现(2)---usrQBN2243 文本解析到对象协议规范
- getch()、_sleep() 函数的正确用法
- Leetcode20: Valid Parentheses
- #Mac OS X下Maven部署
- Leetcode. 135 Candy(Hard)
- IE浏览器使用JS打印部分网页
- Atitit 发帖机实现(3 )---usrQBN023 js提交ajax内容到后端规范与标准化
- php ob系列的函数
- 初试Unity 3D——实例的创建与销毁
- JS-DHTML模型
- 操作系统---进程调度算法
- Android 实现动态生成菜单
- Android 获取内存信息---ActivityManager的使用