Leetcode 135. 分發糖果 (拓撲排序)
阿新 • • 發佈:2021-01-04
Description
Solution
以孩子間的關係建單向邊,每個點在拓撲排序中的層數之和即為答案
Hint
評分相同的孩子需要建雙向邊
Code
class Solution {
public:
#define maxn 200005
int d[maxn];
vector<int>edge[maxn];
inline void add(int u,int v) {
edge[u].push_back(v);
d[v]++;
}
int candy(vector< int>& ratings) {
int n = ratings.size();
for(int i = 0;i < n;++i) edge[i].clear(), d[i] = 0;
for(int i = 0;i < n;++i) {
if(i != n-1) {
if(ratings[i] > ratings[i+1]) add(i+1,i);
if(ratings[i] < ratings[i+1]) add(i,i+ 1);
}
if(i != 0) {
if(ratings[i] > ratings[i-1]) add(i-1,i);
if(ratings[i] < ratings[i-1]) add(i,i-1);
}
}
queue<int>q;
int cnt = 1, res = 0;
for(int i = 0;i < n;++i) if(d[i]==0) q.push(i), q.push(cnt);
while(!q.empty()) {
int now = q.front();q.pop();
cnt = q.front();q.pop();
res += cnt;
for(auto v : edge[now]) {
if(--d[v] == 0) q.push(v), q.push(cnt+1);
}
}return res;
}
};