set 容器的巧妙利用

来源:互联网 发布:windows 官网 编辑:程序博客网 时间:2024/06/06 02:09

Egg pain's hzf


Time Limit: 3000MS Memory Limit: 65535KBSubmissions: 45 Accepted: 10
Description

hzf is crazy about reading math recently,and he is thinking about a boring problem.

Now there are n integers Arranged in a line.For each integer,he wants to know the maximum integer in its left which is less than it.

Input

The input consists of multiple test cases.

For each case,the first line contains one integer n(0<n<=100000),indicating the number of integers.

The second line contains n integers,indicating the integers from left to right,marked a1…an.(0<ai<=10^9).

Output

For each case,there are n integers,indicating the maximum integer in ai's left which is less than it.If it doesn's exist,output -1.

Sample Input

51 2 3 4 55 5 4 3 2 1

Sample Output

-1 1 2 3 4
-1 -1 -1 -1 -1
这题一开始我直接暴力,发现超时,其实想都不要想,两个for直接肯定会超时,然后想不到方法了,后来队长教我了:
#include <iostream>#include <cstdio>#include <cstring>#include <set>#include <algorithm>using namespace std;const int N=100005;int a[N];int n;int main() {    int b;    while(scanf("%d",&n)!=EOF) {        set<int>M;        set<int>::iterator it;        for(int i=0; i<n; i++) {            scanf("%d",&a[i]);            int k=a[i];            it=M.lower_bound(a[i]);            if(it==M.begin())a[i]=-1;            else {                --it;                a[i]=*it;            }            M.insert(k);        }        printf("%d",a[0]);        for(int i=1; i<n; i++) {            printf(" %d",a[i]);        }        printf("\n");    }    return 0;}
0 0