My intuition told me that it is a line-scan process.. and yes it is. First, we sort all (a,b,k) by indexstart-end, then we do a line scan. And in C++ you HAVE TO use 'long long'
#include <cmath> #include <cstdio> #include <vector> #include <map> #include <set> #include <unordered_set> #include <string> #include <climits> #include <iostream> #include <algorithm> #include <unordered_map> #include <unordered_set> using namespace std; struct Rec { Rec(long long v, int rx, int b) :val(v), x(rx), bStart(b){} long long val; int x; int bStart; }; bool comp(const Rec &r1, const Rec &r2) { if (r1.x != r2.x) return r1.x < r2.x; return r1.bStart > r2.bStart; } int main() { int n, m; cin >> n >> m; vector<Rec> recs; while (m--) { long long a, b, k; cin >> a >> b >> k; recs.push_back(Rec(k, a, 1)); recs.push_back(Rec(k, b, 0)); } std::sort(recs.begin(), recs.end(), comp); long long curr = 0, ret = -1; for (auto &r : recs) { if (r.bStart == 1) { curr += r.val; } else { curr -= r.val; } ret = std::max(ret, curr); } cout << ret << endl; return 0; }