http://acm.uestc.edu.cn/problem.php?pid=1558

  1 #include <cstdio>
  2 #include <cstring>
  3 #include <algorithm>
  4 using namespace std;
  5 #define lson l,m,rt<<1
  6 #define rson m+1,r,rt<<1|1
  7 #define maxn 100005
  8 #define LL long long 
  9 #define inf (LL)1e9*maxn
 10 int sorted[maxn]={
 11     1
 12 };
 13 struct node{
 14     LL cost;
 15 }setree[maxn<<2];
 16 struct op{
 17     int v,r,t;
 18 }mes[maxn];
 19 bool cmp(struct op a,struct op b)
 20 {
 21     return a.v<b.v;
 22 }
 23 void build(int l,int r,int rt)
 24 {
 25     setree[rt].cost=inf;
 26     if(l==r){
 27         if(l==0)
 28         setree[rt].cost=0;
 29         return;
 30     }
 31     int m=(l+r)>>1;
 32     build(lson);
 33     build(rson);
 34 }
 35 int binsearch1(int l,int r,int num,int &pos)
 36 {
 37     if(l>r)
 38     return pos;
 39     int m=(l+r)>>1;
 40     if(num<=sorted[m]){
 41         pos=m;
 42         return binsearch1(l,m-1,num,pos);
 43     }
 44     return binsearch1(m+1,r,num,pos);
 45 }
 46 int binsearch(int l,int r,int num)
 47 {
 48     int m=(l+r)>>1;
 49     if(num==sorted[m])
 50     return m;
 51     if(num<sorted[m])
 52     return binsearch(l,m-1,num);
 53     return binsearch(m+1,r,num);
 54 }
 55 void pushup(int rt)
 56 {
 57     setree[rt].cost=min(setree[rt<<1].cost,setree[rt<<1|1].cost);
 58 }
 59 void update(int l,int r,int rt,int pos,LL num)
 60 {
 61     if(l==r){
 62         setree[rt].cost=min(setree[rt].cost,num);
 63         return;
 64     }
 65     int m=(l+r)>>1;
 66     if(pos<=m)
 67     update(lson,pos,num);
 68     else
 69     update(rson,pos,num);
 70     pushup(rt);
 71 }
 72 LL query(int l,int r,int rt,int L,int R)
 73 {
 74     if(L<=l&&r<=R)
 75     return setree[rt].cost;
 76     int m=(l+r)>>1;
 77     LL ans=inf;
 78     if(L<=m)
 79     ans=min(ans,query(lson,L,R));
 80     if(R>m)
 81     ans=min(ans,query(rson,L,R));
 82     return ans;
 83 }
 84 int main()
 85 {
 86     int t,cas=1;
 87     scanf("%d",&t);
 88     while(t--){
 89         int n,m;
 90         scanf("%d%d",&n,&m);
 91         for(int i=1;i<=n;i++){
 92             scanf("%d%d%d",&mes[i].v,&mes[i].r,&mes[i].t);
 93             sorted[i]=mes[i].v;
 94         }
 95         sort(mes+1,mes+n+1,cmp);
 96         sort(sorted+1,sorted+n+1);
 97         int k=0;
 98         for(int i=1;i<=n;i++)
 99         if(sorted[i]!=sorted[i-1])
100         sorted[++k]=sorted[i];
101         build(0,k,1);
102         int pos;
103         for(int i=1;i<=n;i++){
104             pos=-1;
105             int l=binsearch1(0,k,mes[i].r,pos);
106             int r=binsearch(0,k,mes[i].v);
107             LL ans=query(0,k,1,l,r-1);
108             update(0,k,1,r,ans+mes[i].t);
109         }
110         int l=binsearch1(0,k,m,pos);
111         LL ans=query(0,k,1,l,k);
112         if(ans==inf)
113         ans=-1;
114         printf("Case #%d: %lld\n",cas++,ans);
115     }
116     return 0;
117 }
AC Code