题意:给出n个区间和X,每个区间有左右边界和价值,li,ri,x。然后问从这n个区间找出2个不重合的区间,他们的区间长度和为x,并且价值最小。
解答:方法一:预处理:记录所有以某个点为左端点、右端点的区间长度和价值。枚举以每个点为左端点和右端点的所有区间。记录每个以该点为右端点的区间的价值的最小值。然后从第二个点为起点更新最小值。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
const long long INF = 1e18;
using namespace std;
struct w
{
int d,cost;
};
const int MAXN = 200000 + 20;
vector<w> ll[MAXN],rr[MAXN];
w W[MAXN];
long long c[MAXN];
int main()
{
int n,x;
while(~scanf("%d%d",&n,&x))
{
long long ans = INF;
for(int i = 0;i <= 200000;i++)
c[i] = INF;
int tx,ty,tz;
for(int i = 0;i < n;i++)
{
scanf("%d%d%d",&tx,&ty,&tz);
W[i].d = ty - tx + 1;
W[i].cost = tz;
ll[tx].push_back(W[i]);
rr[ty].push_back(W[i]);
}
for(int i = 1;i <= 200000;i++)
{
for(int j = 0;j < ll[i].size();j++)
{
int t = ll[i][j].d;
if(x - t >= 0)
ans = min(ans,c[x-t] + ll[i][j].cost);
}
for(int j = 0;j < rr[i].size();j++)
{
c[rr[i][j].d] = min(c[rr[i][j].d],(long long)rr[i][j].cost);
}
}
if(ans == INF)
puts("-1");
else
printf("%64d\n",ans);
}
return 0;
}
方法二:按照左端点和右端点的大小分别排序。两个区间:要保证第一个区间的右端点小于第二个区间的左端点。每次记录第一个区间的大小的最小值,第一个区间的坐标可以不断增加。枚举第二个区间,不断增加第一个区间的坐标。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const long long INF = 1e18;
const int MAXN = 200000 + 20;
struct W
{
int x,y,c;
};
W wx[MAXN];
W wy[MAXN];
bool cmp1(W a,W b)
{
if(a.x == b.x)
return a.y < b.y;
else
return a.x < b.x;
}
bool cmp2(W a,W b)
{
if(a.y == b.y)
return a.x < b.x;
else
return a.y < b.y;
}
int main()
{
int n,x;
while(~scanf("%d%d",&n,&x))
{
for(int i = 0;i < n;i++)
{
scanf("%d%d%d",&wx[i].x,&wx[i].y,&wx[i].c);
wy[i] = wx[i];
}
sort(wx,wx+n,cmp1);
sort(wy,wy+n,cmp2);
int j = 0;
long long cost[MAXN];
long long ans = INF;
for(int i = 0;i < MAXN;i++)
cost[i] = INF;
for(int i = 0;i < n;i++)
{
int t = wx[i].y - wx[i].x + 1;//第二个
while(j < n && wy[j].y < wx[i].x)
{
cost[wy[j].y - wy[j].x + 1] = min((long long)wy[j].c,cost[wy[j].y - wy[j].x + 1]);
j++;
}
if(x>t)
ans = min(ans,(long long)wx[i].c+cost[x-t]);
}
if(ans==INF)
puts("-1");
else
cout << ans << endl;
}
return 0;
}