Hacker, pack your bags!
题目连接: CodeForces - 822C题目大意:给你n个旅券,上面有开始时间l,结束时间r,和花费cost,要求选择两张时间不相交的旅券时间长度相加为x,且要求花费最少。
思路:保存所有端点, 并将端点由小到大排序, 端点相同的左端点在前;用数组sum[i]记录长度为i的一段的最小花费, if(sum[i]==0)表示不存在长度为i的一段;
由小到大遍历所有端点:
1)遇到左端点记录该段时间宽度t, if(t>=x)则这段时间一定不满足, 因为要选两张长度为x的, if(sum[x-t]==0)此时找不到一段与该段相加为x;否则一定存在一段时间加该段为x, 更新最小花费;
2)遇到右端点记录该段时间宽度t, if(sum[t]==0||sum[t]>cost)(cost为该段时间的花费)此时更新sum[t]的值;
#include <iostream>
#include <map>
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 2e5+10;
const int INF = 2e9+1;
struct node{
int l, r, c, type;
node(){};
node(int l0, int r0, int c0, int t){
l=l0, r=r0, c=c0, type=t;
}
};
bool cmp(node a, node b){
if(a.l==b.l) return a.type<b.type;
return a.l<b.l;
}
vector<node> vec;
int sum[maxn];
int main(){
int n, x, r, l, c, t;
scanf("%d%d", &n, &x);
for(int i=0; i<n; i++){
scanf("%d%d%d", &l, &r, &c);
vec.push_back(node(l, r, c, -1));
vec.push_back(node(r, l, c, 1));
}
sort(vec.begin(), vec.end(), cmp);
int len=vec.size();
int time;
int ans=INF;
for(int i=0; i<len; i++){
if(vec[i].type==-1){
time=vec[i].r-vec[i].l+1;
if(time>=x||!sum[x-time]) continue;
ans=min(ans, sum[x-time]+vec[i].c);
}
else{
time=vec[i].l-vec[i].r+1;
if(!sum[time]||sum[time]>vec[i].c)
sum[time]=vec[i].c;
}
}
if(ans==INF) printf("-1\n");
else printf("%d\n", ans);
return 0;
}