#include using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); int N,Q; cin >> N >> Q; vector> P(N); vector> LRC(N); for(int i=0; i> l >> r >> c,l--; for(int p=l; p one(N,-1); map,long long> memo; auto f = [&](auto f,int l,int r) -> long long { if(l >= r) return 0; if(l+1 == r){ if(one.at(l) != -1) return one.at(l); int now = 0; for(auto pos : P.at(l)){ auto [L,R,c] = LRC.at(pos); if(l == L && r == R) now = max(now,c); } return one.at(l) = now; } if(memo.count({l,r})) return memo[{l,r}]; int m = (l+r)/2; long long ret = f(f,l,m)+f(f,m,r); for(auto pos : P.at(m)){ auto [L,R,c] = LRC.at(pos); if(l <= L && L < m && m < R && R <= r) ret = max(ret,c+f(f,l,L)+f(f,R,r)); } memo[{l,r}] = ret; return ret; }; while(Q--){ int a,b; cin >> a >> b,a--,b--; auto [l1,r1,c1] = LRC.at(a); auto [l2,r2,c2] = LRC.at(b); if(l1 > l2) swap(l1,l2),swap(r1,r2),swap(c1,c2); if(l2 < r1){cout << "-1\n"; continue;} cout << f(f,0,l1)+f(f,r1,l2)+f(f,r2,N)+c1+c2 << "\n"; } }