Passing the Message

╰+攻爆jí腚メ 2022-06-12 12:07 320阅读 0赞

![Image 1][]

![Image 1][]![Image 1][]

![Image 1][]

![Image 1][]![Image 1][]

题意:传信息,左边传给比自己矮的人中最高的那个,右边也是如此,输出每个人左右的被传递者,若左右没有比自己矮的人,输出0.

思路:维护一个从大到小的单调栈,最后一个被pop掉的元素是最大的。

  1. #include<stdio.h>
  2. #include<stack>
  3. #include<memory>
  4. using namespace std;
  5. #define maxn 50010
  6. #define ll long long
  7. ll a[maxn];
  8. ll l[maxn], r[maxn];
  9. stack<ll>s1, s2;
  10. int main(){
  11. int N, T, cnt=0;
  12. scanf("%d", &T);
  13. while(T--)
  14. {
  15. memset(l, 0, sizeof(l));//每一次案例须重新初始化的必须重新初始化。
  16. memset(r, 0, sizeof(r));
  17. while(!s1.empty())s1.pop();
  18. while(!s2.empty())s2.pop();
  19. scanf("%d", &N);
  20. for(int i=1; i<=N; i++)
  21. {
  22. scanf("%lld", a+i);
  23. }
  24. for(int i=1; i<=N; i++)//左边。
  25. {
  26. while(!s1.empty() && a[i]>a[s1.top()])
  27. {
  28. l[i]=s1.top();//其实只有最后一次有用。
  29. s1.pop();
  30. }
  31. s1.push(i);
  32. }
  33. for(int i=N; i>=1; i--)//右边。
  34. {
  35. while(!s2.empty() && a[i]>a[s2.top()])
  36. {
  37. r[i]=s2.top();
  38. s2.pop();
  39. }
  40. s2.push(i);
  41. }
  42. printf("Case %d:\n", ++cnt);
  43. for(int i=1; i<=N; i++)
  44. {
  45. printf("%lld %lld\n", l[i], r[i]);
  46. }
  47. }
  48. return 0;
  49. }

本人语拙,如有不懂,尽请留言,如有不足,不吝赐教。

[Image 1]:

发表评论

表情:
评论列表 (有 0 条评论,320人围观)

还没有评论,来说两句吧...

相关阅读

    相关 pass

    在linux服务器nginx环境下rewrite规则怎么写 一.正则表达式匹配,其中: \~为区分大小写匹配 \~\为不区分大小写匹配 \!~和!~\分别为区分大小