Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

用了划分树-157MS AC!

Posted by lz1 at 2011-06-18 17:14:18 on Problem 1442
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
using std::sort;

#define MAX_N 100001
struct tree_node 
{
       int l, r;
};
tree_node tt[MAX_N << 2];
int sorted[MAX_N];
int tl[20][MAX_N];
int val[20][MAX_N];
int n, m;

inline void swap(int& a, int& b) 
{
       int t = a;
       a = b, b = t;
}

void build(int l, int r, int d, int v) 
{
     tt[v].l = l, tt[v].r = r;
     if (l == r) return ;
     int mid = (l + r) >> 1, ls = mid - l + 1, ml = sorted[mid];
     for (int i = l; i <= r; i++)
         if (val[d][i] < ml)
            ls--;
     int lp = l, rp = mid + 1, sa = 0;
     for (int i = l; i <= r; i++) 
     {
         if (i == l)tl[d][i] = 0;
         else tl[d][i] = tl[d][i - 1];
         if (val[d][i] < ml)
            tl[d][i]++, val[d + 1][lp++] = val[d][i];
         else if (val[d][i] > ml)
                 val[d + 1][rp++] = val[d][i];
              else if (sa < ls)
                      sa++, tl[d][i]++, val[d + 1][lp++] = ml;
                   else val[d + 1][rp++] = ml;
     }
	 build (l, mid, d + 1, v << 1);
	 build (mid + 1, r, d + 1, (v << 1) | 1);
}

int query(int l, int r, int k, int d, int v) 
{
    if (l == r)
       return val[d][l];
    int s, ss, nl, nr;
    if (l == tt[v].l)
       s = tl[d][r], ss = 0;
    else s = tl[d][r] - tl[d][l - 1], ss = tl[d][l - 1];
    if (s >= k) 
    {
       nl = tt[v].l + ss;
       nr = tt[v].l + ss + s - 1;
       return query (nl, nr, k, d + 1, v << 1);
    }
    else 
    {
         int mid = (tt[v].l + tt[v].r) >> 1;
         int bb = l - tt[v].l - ss;
         int b = r - l + 1 - s;
         nl = mid + bb + 1;
         nr = mid + bb + b;
         return query (nl, nr, k - s, d + 1, (v << 1) | 1);
    }
}

int main(void) 
{
    freopen ("1442.in", "r", stdin);
    freopen ("1442.out", "w", stdout);
    while (scanf ("%d%d", &n, &m) != EOF) 
    {
          for (int i = 1; i <= n; i++) 
          {
              scanf ("%d", sorted + i);
              val[0][i] = sorted[i];
          }
          sort (sorted + 1, sorted + 1 + n);
          build (1, n, 0, 1);
                    for (int i = 1, x; i <= m; i++) 
          {
              scanf ("%d", &x);
              printf ("%d\n", query(1, x, i, 0, 1));
          }
    }
	return 0;
}


Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator