给定n个区间,l,r,cost,求其中2个区间是否能凑成总长为x,并且费用最小。
没看懂题解,先记录下。
从左往右遍历,遇到左端点就更新答案,否则更新bestcost[j],长度为j天时的最小费用。
ps:n = 2e5 cost = 1e9 max = 2e14需要long long
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 2e5 + 5;
typedef long long ll;
typedef pair<int, ll> pr;
const ll INF = 2e15;
ll bestcost[maxn];
vector<pr> L[maxn],R[maxn];
int main()
{
int n,x;
scanf("%d%d",&n,&x);
int l,r;
ll cost;
for (int i = 0; i < n; i ++) {
scanf("%d%d",&l,&r);
cin >> cost;
L[l].push_back({r - l + 1,cost});//以第l天为左端点的区间
R[r].push_back({r - l + 1,cost});
}
for (int i = 0; i < maxn; i ++) {
bestcost[i] = INF;
}
ll m = INF;
for (int i = 0; i < maxn; i ++) {
for(int j = 0;j < L[i].size();j ++)
{
if(L[i][j].first >= x) continue;
m = min(m , bestcost[x - L[i][j].first] + L[i][j].second );
}
for (int j = 0; j < R[i].size(); j ++) {
if(R[i][j].first >= x) continue;
bestcost[R[i][j].first] = min(bestcost[R[i][j].first] , R[i][j].second );
}
}
if(m == INF) m = -1;
cout << m << endl;
return 0;
}