Problem Description
A simple problem Problem Description You have a multiple set,and now there are three kinds of operations:
1 x : add number x to set
2 : delete the minimum number (if the set is empty now,then ignore it)
3 : query the maximum number (if the set is empty now,the answer is 0)
Input
The first line contains a number N (N≤106),representing the number of operations. Next N line ,each line contains one or two numbers,describe one operation. The number in this set is not greater than 109.
Output
For each operation 3,output a line representing the answer.
Sample Input
6
1 2
1 3
3
1 3
1 4
3
Sample Output
3
4
题意:有个数列,有三种操作:
1 X 把X加入数列中;
2 去掉数列中最小数;
3 输出数列中最大数。
由于每次输出的都是最大数,所以只要记录最大数就可以了。去掉数的时候不一定要去掉最小数,只要去掉不是最大数的任意一个数都可以,所以还要一个变量记录数列中有多少个数。现在问题就简单了,输入1 X时,判断X和数列中最大数比较,如果X大数列中最大值变为X并且数列个数加1,否则只要数列个数加1.输入 2 时,数列个数减就可以了。输入 3 时直接输出最大值就可以了。
还有一种方法叫 STL很简单。就不多说了。
普通:
1 #include<cstdio> 2 #include<cstring> 3 using namespace std; 4 int main() 5 { 6 int a=-0x7FFFFFFF,t=0,n; 7 int x,y; 8 scanf("%d",&n); 9 while (n--) 10 { 11 scanf("%d",&x); 12 if (x==1) 13 { 14 scanf("%d",&y); 15 if (y>a) a=y; 16 t++; 17 } 18 if (x==2) 19 { 20 if (t) t--; 21 if (t==0) a=-0x7FFFFFFF; 22 } 23 if (x==3) 24 { 25 if (t==0) printf("0\n"); 26 else printf("%d\n",a); 27 } 28 } 29 return 0; 30 }
STL
1 #include<cstdio> 2 #include<cstring> 3 #include<set> 4 using namespace std; 5 set<int>s; 6 set<int>::iterator it; 7 int main() 8 { 9 int n,x,y; 10 scanf("%d",&n); 11 s.clear(); 12 while (n--) 13 { 14 scanf("%d",&x); 15 if (x==1) 16 { 17 scanf("%d",&y); 18 s.insert(y); 19 } 20 if (x==2) 21 { 22 if (!s.empty()) 23 { 24 it=s.begin(); 25 s.erase(it); 26 } 27 } 28 if (x==3) 29 { 30 if (s.empty()) printf("0\n"); 31 else 32 { 33 it=s.end(); 34 it--; 35 printf("%d\n",*it); 36 } 37 } 38 } 39 return 0; 40 }