STL中map取最大最小键值方法(POJ3481)
首先介绍一下STL中map的架构:
结果:
SGI STL map以红黑树为低层级制,每个节点的内容是一个pair。pair的第一个元素被视为键值(key),第二个元素被视为实值(value)。
那么如何用O(1)的时间去取得最小或者最大的key值相对应的<key,value>对(注意不是value,因为map是以key值即键值来构建平衡树的)。
下面呈现一个代码:
- #include<iostream>
- #include<map>
- using namespace std;
- int main()
- {
- map<int,char> m;
- m[8] = 'a';
- m[6] = 'b';
- m[11] = 'c';
- m[5] = 'd';
- m[7] = 'e';
- m[10] = 'f';
- m[13] = 'g';
- m[12] = 'h';
- m[15] = 'i';
- map<int,char>::const_iterator it = m.begin();
- while( it!=m.end() )
- {
- cout<<it->first<<" "<<it->second<<endl;
- it++;
- }
- <strong> it = m.begin();</strong>//相当于获取了平衡树最左下面(most left)的结点的迭代器
- cout<<"min "<<it->first<<" "<<it->second<<endl;//最小的key值
- <strong>it = m.end();</strong>//相当于获取了平衡树最右下面(most right)的结点的迭代器
- <strong>it--; </strong>
- cout<<"max "<<it->first<<" "<<it->second<<endl; //最大的key值
- system("pause");
- return 0;
- }
结果:
可见it在遍历的时候是按照key值的升序顺序迭代的,相当于中序遍历了平衡树。从上面代码可以看到如何在O(1)的时间内完成操作。当然如果是想获取value值的最大最小值所对应的键值对,我认为有三种方法:1.将map转存到vector(类型为pair)中,然后将vector调用sort按照value进行排序,然后取得最大最小值,时间复杂度为O(nlogn);2.遍历map中的value值,取得最大最小值,时间复杂度为O(n);3.如果条件允许,为什么不把value的值当做map中的key进行存储呢?map会自动的维护平衡树,插入和删除元素平衡树的性质都不会改变。那么就可以在O(1)的时间内获取最大最小值了。
呈上一道题目:http://poj.org/problem?id=3481
这道题TLE了N次,以为是函数调用的问题,最后才发现是因为输入的时候用的cin而不是scanf,估计在大数据量输入的时候会超时吧。
- #include<iostream>
- #include<map>
- #include<cstring>
- #include<stdio.h>
- #include<cstdlib>
- using namespace std;
- map<int,int> m;
- map<int,int>::const_iterator it;
- inline int serve_highest_pri()
- {
- if( m.size()==0 )
- return 0;
- it = m.end();
- it--;
- int res = it->second;
- m.erase(it->first);
- return res;
- }
- inline int serve_lowest_pri()
- {
- if( m.size()==0 )
- return 0;
- it = m.begin();
- int res = it->second;
- m.erase(it->first);
- return res;
- }
- int main()
- {
- int k,p,n,res;
- while( scanf("%d",&n) )
- {
- if(n==0)
- {
- break;
- }
- else if(n==1)
- {
- scanf("%d%d",&k,&p);
- m[p] = k;
- continue;
- }
- else if(n==2)
- {
- res = serve_highest_pri();
- if(res==0)
- {
- cout<<0<<endl;
- }
- else
- {
- cout<<res<<endl;
- }
- continue;
- }
- else
- {
- res = serve_lowest_pri();
- if(res==0)
- {
- cout<<0<<endl;
- }
- else
- {
- cout<<res<<endl;
- }
- }
- }//while
- system("pause");
- return 0;
- }
Run ID | User | Problem | Result | Memory | Time | Language | Code Length | Submit Time |
12378323 | niuliguo | 3481 | Accepted | 776K | 454MS | G++ | 1465B | 2013-12-14 16:43:41 |
注明出处:http://blog.****.net/lavorange/article/details/17320951