1 solutions

  • 0
    @ 2022-1-8 16:31:18

    双重for循环,非常幸运没超时,代码简单,就不过多阐述

    #include <bits/stdc++.h>
    using namespace std;
    const int N=1e5+7;
    int w[N];
    int main(){
    	int t,n;
    	cin>>t;
    	while(t--){
    		cin>>n;
    		for(int i=0;i<n;i++){
    			scanf("%d",&w[i]);
    		}
    		for(int i=0;i<n;i++){
    			int flag=0;
    			for(int j=i-1;j>=0;j--){
    				if(w[j]<w[i]&&i!=n-1){
    					flag=1;
    					cout<<j<<" ";
    					break;
    				}
    				else if(w[j]<w[i]&&i==n-1){
    					flag=1;
    					cout<<j;
    					break;
    				}
    			}
    			if(flag==0&&i!=n-1) cout<<-1<<" ";
    			else if(flag==0&&i==n-1) cout<<-1;
    		}
    		cout<<endl; 
    	}
    	return 0;
    }
    

    下面是刘龙浩学长与谢老师的更厉害的思想, 简单分析就是将每个数的答案进行存储,然会对后面的数求解时,只需要根据前面的答案来进行找,这样就可以快速查找了,讲得很抽象,具体看代码

    #include<cstring>
    #include<cstdio>
    #define N 1000100
    using namespace std;
    
    int pre[N],h[N],n;
    int main()
    {
    	int  t;
    	scanf("%d",&t);
        while (t--)
        {
    		scanf("%d",&n);
            h[0]=-1;pre[0]=0;
            for (int i=1;i<=n;++i)
                scanf("%d",h+i);//输入
            for (int i=1;i<=n;++i)
            {
                int j=i-1;
                while (j&&h[j]>=h[i])
                    j=pre[j];//根据前面的答案进行寻找
                pre[i]=j;//储存每个数的答案
            }
            for (int i=1;i<=n;++i)
                printf("%d%c",pre[i]-1," \n"[i==n]);
        }
    	return 0;
    } 
    
    • 1

    Information

    ID
    1531
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    5
    Tags
    # Submissions
    44
    Accepted
    14
    Uploaded By