結果

問題 No.924 紲星
ユーザー leaf_1415leaf_1415
提出日時 2019-11-08 23:07:19
言語 C++11
(gcc 11.4.0)
結果
TLE  
実行時間 -
コード長 2,140 bytes
コンパイル時間 1,160 ms
コンパイル使用メモリ 82,912 KB
実行使用メモリ 26,432 KB
最終ジャッジ日時 2023-10-13 04:46:08
合計ジャッジ時間 7,616 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
26,432 KB
testcase_01 AC 1 ms
4,348 KB
testcase_02 AC 2 ms
4,348 KB
testcase_03 AC 5 ms
4,348 KB
testcase_04 AC 3 ms
4,348 KB
testcase_05 AC 8 ms
4,348 KB
testcase_06 AC 4 ms
4,348 KB
testcase_07 AC 3 ms
4,352 KB
testcase_08 TLE -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <cmath>
#include <set>
#include <stdio.h>
#define llint long long

using namespace std;
typedef pair<llint, llint> P;
typedef pair<P, P> Q;

int n, Qnum, B;
int a[200005];
vector<Q> qvec;
llint ans[200005];
multiset<int> head, tail;
llint hsum, tsum;

void adjust(llint m)
{
	while((int)head.size() > (m+1)/2){
		auto it = head.end(); it--;
		tsum += *it, hsum -= *it;
		tail.insert(*it), head.erase(it);
	}
	while((int)head.size() < (m+1)/2){
		hsum += *tail.begin(), tsum -= *tail.begin();
		head.insert(*tail.begin()), tail.erase(tail.begin());
	}
}

void add(llint x)
{
	llint m = head.size() + tail.size();

	if(head.size() == 0) head.insert(x), hsum += x;
	else{
		auto it = head.end(); it--;
		if(*it >= x) head.insert(x), hsum += x;
		else tail.insert(x), tsum += x;
	}

	m++;
	adjust(m);

}

void erase(llint x)
{
	llint m = head.size() + tail.size();

	if(head.count(x)) head.erase(head.lower_bound(x)), hsum -= x;
	else tail.erase(tail.lower_bound(x)), tsum -= x;

	m--;
	adjust(m);
}

llint get()
{
	auto it = head.end(); it--;
	llint med = *it;
	llint ret = tsum - med * (llint)tail.size();
	ret += med * (llint)head.size() - hsum;
	return ret;
}

int main(void)
{
	//ios::sync_with_stdio(0);
	//cin.tie(0);

	//cin >> n >> Qnum;
	scanf("%d %d", &n, &Qnum);
	for(int i = 1; i <= n; i++) scanf("%d", &a[i]);//cin >> a[i];
	B = sqrt(n);

	int l, r;
	for(int q = 1; q <= Qnum; q++){
		//cin >> l >> r;
		scanf("%d %d", &l, &r);
		qvec.push_back(Q(P(l/B, r), P(l, q)));
	}
	sort(qvec.begin(), qvec.end());

	l = qvec[0].second.first, r = qvec[0].first.second;
	for(int i = l; i <= r; i++) add(a[i]);
	ans[qvec[0].second.second] = get();

	for(int i = 1; i < qvec.size(); i++){
		llint nl = qvec[i].second.first, nr = qvec[i].first.second;
		while(l > nl) l--, add(a[l]);
		while(r < nr) r++, add(a[r]);
		while(l < nl) erase(a[l]), l++;
		while(r > nr) erase(a[r]), r--;
		llint qid = qvec[i].second.second;
		ans[qid] = get();
	}

	for(int q =	1; q <= Qnum; q++) printf("%lld\n", ans[q]); //cout << ans[q] << "\n";
	flush(cout);

	return 0;
}
0