Give Me This Pizza

法兴德
2023-12-01

Today Abdalrahman and Ali have one hour break, so they decided to spend it in the Innovation Programming Lab to invent new game.

After a deep thinking they invented a new game that is played using an array a. The goal of the game is to find for each value in the array the nearest larger value to it from the right. (i.e. for the ith value in the array, the goal is to find the value in the nearest jth index, such that (1  ≤  i  <  j  ≤  n) and (aj  >  ai)). If the nearest larger value does not exist, then the answer is “-1”.

Abdalrahman and Ali thought that this game is very hard and no one can solve it, so they wrote it in the white board inside the lab, and under it they wrote the following statement: “If you solve this game correctly we will give you a very big pizza”.

Yosef enter the lab after Abdalrahman and Ali left it. When he saw the game, he decided to solve it to take the pizza. Yosef is very hungry currently so you decided to help him to solve the game as soon as possible. Can you?

Input

The first line contains an integer n (1  ≤  n  ≤  105), where n is the length of the array a.

The second line contains n integers a1, a2, …, an (1  ≤  ai  ≤  50), giving the array a.

Output

Print n integers b1, b2, …, bn, where bi is the nearest larger value for the ith value in array a. If such value does not, then bi must be “-1” (without quotes).

Examples

Input
5
2 1 3 9 4

Output
3 3 9 -1 -1

题目大意: 给定一个数列,找到每个数右边比它大的最近的数并输出,若不存在输出-1。
由于传统思路会超时,因此这道题用一个比较骚的操作。

由于数字的范围是1-50,因此开一个长度为50的数组记录每个数出现的位置。



int main(){
    int n,i,j,num[100010],rec[55];
    int fff;
    while(cin>>n){
        stack<int>ans;
        bool flag=1;
        int mmin;
        while(!ans.empty())
            ans.pop();
        memset(rec,0,sizeof(rec));
        for(i=0;i<n;i++)
            cin>>num[i];
        for(i=n-1;i>=0;i--){  //循环从右向左跑
            rec[num[i]]=i;    //记录每个数出现的位置并不断更新(以得到最靠左的那个) 如果数字9在三号位置出现了,就有rec[9]==3;
            mmin=100010;
            for(j=num[i]+1;j<=50;j++){    //循环从当前num[i]的下一个值往上跑(如果num[i]==8,就从9-50里面找一个位置最靠左即表示位置的数值最小的) 
                if(rec[j]&&rec[j]<mmin){
                    mmin=rec[j];
                    fff=j;
                }
            }
            if(j==51&&mmin==100010) ans.push(-1);
            else ans.push(fff);

        }
        while(!ans.empty()){
            if(flag){
            flag=!flag;
            cout<<ans.top();
            }
            else cout<<" "<<ans.top();
            ans.pop();
        }   
        cout<<endl;     
    }

    return 0;
}
 类似资料:

相关阅读

相关文章

相关问答