【帮人发帖】为什么还卡常?
查看原帖
【帮人发帖】为什么还卡常?
941962
Kasa_楼主2023/5/13 23:17

帮同机房好友发帖,虽然常数大了点

https://www.luogu.com.cn/record/110302677

其实不需要发代码吧,因为 1.19s,1.18s1.19s,1.18s 应该是卡常的标志吧。

还是发一发吧:

#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll n,a[3000005],ans[3000005];//ans数组用于记录答案 
stack<ll> st;
int main(){
    cin >> n;
    for(int i=1;i<=n;i++)
        cin >> a[i];
    a[n+1]=LONG_LONG_MAX;
    for(int i=1;i<=n+1;i++){
        if(!st.empty()){
			while((!st.empty())&&a[st.top()]<=a[i]){
				ans[st.top()]=i;
				st.pop();
			}
		}
		st.push(i);
    }//每个元素只有一次的出栈和入栈,所以是O(n)的 
    for(int i=1;i<=n;i++){
    	if(ans[i]!=n+1)
			cout << ans[i] << " ";
		else
			cout << "0 ";
	}
    return 0;
}

有逝私信找@heike305 ,我没空,只是代人发帖。

建议把题目数据改为 n≤1∗105n\le1*10^5 吧,毕竟是为了卡掉 O(n2)O(n^2) 暴力做法,使用 O(n)O(n) 单调栈算法。

2023/5/13 23:17
加载中...