HDU 4302 Holedox Eating
令我及其伤心的一题啊。比赛的时候想用HASH写,波波写出来果断TLE。
正解:
1.STL,set
2.优先队列
3.线段树树状数组
线段树:
View Code
#include<stdio.h> #include<stdlib.h> #include<iostream> #include<string.h> #include<algorithm> using namespace std; #define MAXN 401010 const int inf = 0xFFFFFF; struct node { int l, r, num, Lm, Rm; }T[MAXN<<4]; int N, M, L, R, pos; void build( int l,int r, int root) { int mid = (l + r) / 2; T[root].l = l; T[root].r = r; T[root].Lm = inf; T[root].Rm = -inf; T[root].num = 0; if( l == r ) return; build(l, mid, root << 1 ); build(mid + 1, r, (root << 1) + 1); } void insert( int pos, int root) { int mid = (T[root].l + T[root].r) / 2; T[root].num++; if( T[root].l == T[root].r ) { T[root].Lm = T[root].l; T[root].Rm = T[root].r; return; } if( pos > mid ) insert( pos, (root << 1) + 1); else insert( pos, root << 1 ); T[root].Lm = T[root<<1].Lm < T[(root<<1)+1].Lm ? T[root<<1].Lm : T[(root<<1)+1].Lm; T[root].Rm = T[root<<1].Rm > T[(root<<1)+1].Rm ? T[root<<1].Rm : T[(root<<1)+1].Rm; } void query( int p, int root) { int mid = (T[root].l + T[root].r)/2; if( T[root].l == T[root].r ) { if( pos == T[root].r && T[root].num > 0) R = pos; return; } if( p > mid ) { if( T[root*2].num ) L = T[root*2].Rm; query( p, (root << 1) + 1); } else { if( T[root*2+1].num ) R = T[root*2+1].Lm; query( p, root << 1 ); } } void del(int pos, int root ) { int mid = (T[root].l + T[root].r) / 2; if( T[root].num != 0 ) T[root].num--; if( T[root].l == T[root].r ) { if( T[root].num == 0 ) { T[root].Lm = inf; T[root].Rm = -inf; } return; } if( pos > mid ) del(pos, (root << 1) + 1); else del(pos, root << 1 ); T[root].Lm = T[root<<1].Lm < T[(root<<1)+1].Lm ? T[root<<1].Lm : T[(root<<1)+1].Lm; T[root].Rm = T[root<<1].Rm > T[(root<<1)+1].Rm ? T[root<<1].Rm : T[(root<<1)+1].Rm; } int main( ) { int Tn, a, b,dir,steps,f; scanf("%d",&Tn); int cnt = 1; while(Tn--) { scanf("%d%d",&N,&M); long long ans = 0; build(1,N+2,1); ans = 0; pos = 1; dir = 1; for( int i= 1; i <= M; i++) { scanf("%d",&a); if( a == 0 ) { scanf("%d",&b); b++; insert(b, 1); } else { L = inf; R = -inf; query(pos,1); if( L == inf && R == -inf ) continue; int x1 = abs(L - pos); int x2 = abs(R - pos); /*郁闷啊。这样写就一直wa... if( x1 < x2 ) { f = L; steps = x1; } else { f = R; steps = x2; } */ steps = min(x1,x2); if( steps != 0 ) { ans += steps; if( x1 == x2 ) { if( dir == 1 ) pos = R; else pos = L; } else if( x1 > x2 ) { if( dir == 1 ) pos = R; else { pos = R; dir = 1; } } else { if( dir == -1 ) pos = L; else { pos = L; dir = -1; } } } del(pos,1); } } printf("Case %d: %I64d\n",cnt++,ans); } }
posted on 2012-07-24 13:52 more think, more gains 阅读(182) 评论(0) 编辑 收藏 举报