aboutsummaryrefslogtreecommitdiff
path: root/max_score_node_sequence.cpp
blob: b4df5d5416a1c2d5b4aa55e4fd2cf4c2a11246b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include "leetcode.h"

class Solution {
public:
  int maximumScore(vector<int> &scores, vector<vector<int>> &edges) {
    const int n = scores.size();
    vector<vector<int>> adj(n);
    for (const vector<int> &edge : edges) {
      adj[edge[0]].push_back(edge[1]);
      adj[edge[1]].push_back(edge[0]);
    }
    for (vector<int> &a : adj) {
      priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pqpvg;
      for (int v : a) {
        int score = scores[v];
        if (pqpvg.size() < 3 || pqpvg.top().first < score) {
          pqpvg.push({score, v});
          if (pqpvg.size() > 3)
            pqpvg.pop();
        }
      }
      a.resize(pqpvg.size());
      for (int i = a.size() - 1; i >= 0; --i) {
        a[i] = pqpvg.top().second;
        pqpvg.pop();
      }
    }
    int ans = -1;
    for (const vector<int> &edge : edges) {
      int u = edge[0], v = edge[1], base = scores[u] + scores[v];
      for (int x : adj[u]) {
        if (x == v)
          continue;
        for (int y : adj[v]) {
          if (y == u || x == y)
            continue;
          ans = max(ans, base + scores[x] + scores[y]);
        }
      }
    }
    return ans;
  }
};