Leetcode. 135 Candy(Hard)

**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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值