The median of m numbers is after sorting them in order, the middle one number of them ifm is even or the average number of the middle 2 numbers if m is odd. You have an empty number list at first. Then you can add or remove some number from the list.
For each add or remove operation, output the median of the number in the list please.
This problem has several test cases. The first line of the input is an integerT (0<T<=100) indicates the number of test cases. The first line of each test case is an integern (0<n<=10000) indicates the number of operations. Each of the nextn lines is either "add x" or "remove x"(-231<=x<231) indicates the operation.
For each operation of one test case: If the operation is add output the median after addingx in a single line. If the operation is remove and the number x is not in the list, output "Wrong!" in a single line. If the operation is remove and the number x is in the list, output the median after deletingx in a single line, however the list is empty output "Empty!".
2 7 remove 1 add 1 add 2 add 1 remove 1 remove 2 remove 1 3 add -2 remove -2 add -1
Wrong! 1 1.5 1 1.5 1 Empty! -2 Empty! -1
if the result is an integer DO NOT output decimal point. And if the result is a double number , DO NOT output trailing 0s.
1.要维护it1迭代器一直指向中位数
2.代码:
#include<cstdio> #include<set> #include<cstring> #define LL long long using namespace std; multiset<LL> mst; int main() { int t; scanf("%d",&t); while(t--) { multiset<LL>::iterator it; multiset<LL>::iterator it1; mst.clear(); int n; scanf("%d",&n); it1=mst.begin(); for(int i=1; i<=n; i++) { char s[20]; LL x; scanf("%s%lld",s,&x); if(strcmp("add",s)==0) { mst.insert(x); if(mst.size()==1) { it1=mst.begin(); } else if(mst.size()%2==1&&x>=*it1) { it1++; } else if(mst.size()%2==0&&x<*it1) { it1--; } } else { it=mst.find(x); if(it==mst.end()) { printf("Wrong!\n"); continue; } else { if(mst.size()==1) { mst.erase(it); printf("Empty!\n"); continue; } else if(*it1 == x) { it = it1; if(mst.size() % 2 == 0) it1++; else it1--; } else if(mst.size()%2&&x>=*it1) { it1--; } else if(mst.size()%2==0&&x<*it1) { it1++; } mst.erase(it); } } multiset<LL>::iterator it2; if(mst.size()%2) { printf("%lld\n",*it1); } else { it2=it1; it2++; if((*it1+*it2)%2) { printf("%.1lf\n",(*it1+*it2)/2.0); } else { printf("%lld\n",(*it1+*it2)/2); } } } } return 0; }
原文:http://blog.csdn.net/xky1306102chenhong/article/details/45339843