Cod sursa(job #2213469)

Utilizator WebDesignbyTMGhiorghiu Ioan-Viorel WebDesignbyTM Data 16 iunie 2018 14:33:48
Problema Order Scor 5
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.12 kb
#define DM 30001
#include <fstream>
using namespace std;

ifstream fi ("order.in");
ofstream fo ("order.out");
int n, lim, crt, aib[DM];

void upd(int pos, int val)
{
    while (pos <= lim)
    {
        aib[pos] += val;
        pos += pos & (-pos);
    }
}

int query(int pos)
{
    int rez = 0;
    while (pos > 0)
    {
        rez += aib[pos];
        pos -= pos & (-pos);
    }
    return rez;
}

int fnd(int x)
{
    int lo = 1, hi = n, mid;
    while (lo < hi)
    {
        mid = (lo + hi)/2;
        if (query(mid) < x)
            lo = mid + 1;
        else
            hi = mid;
    }
    return lo;
}

int eliminate(int x)
{
	if (query(n) == query(crt))
	{
		crt = 1;
		--x;
	}
	else
	{
		crt = fnd(query(crt) + 1);
		--x;
	}
	x %= query(n);
	if (x <= query(n) - query(crt))
	{
		crt = fnd(query(crt) + x);
		upd(crt, -1);
		return crt;
	}
	x -= query(n) - query(crt);
	crt = fnd(x);
	upd(crt, -1);
	return crt;
}

int main()
{
    fi >> n;
    lim = crt = 1;
    while (lim < n)
        lim <<= 1;
    for (int i = 1; i <= n; ++i)
        upd(i, 1);
    for (int i = 1; i <= n; ++i)
    {
        fo << eliminate(i) << ' ';
    }
}