这道题让我发现了单调栈的唯一性,即可以使得数组记录的位置不会重复。
代码如下:
#include <iostream>
#include <stack>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define mem(a,b) memset (a,b,sizeof(a));
using namespace std;
const int MAX = 1e6 + 10;
int num[MAX] = { 0 };
int leftn[MAX] = { 0 };
int rightn[MAX] = { 0 };
stack<int> s;
stack<int> null;
int main()
{
int t; cin >> t; int k = 0;
while (t--)
{
k++;
s = null;
int n; scanf("%d", &n);
mem(leftn, 0);
mem(rightn, 0);
for (int i = 1; i <= n; i++)
{
scanf("%d", num + i);
while (!s.empty() && num[s.top()] < num[i])
{
leftn[i] = s.top(); s.pop();
}
s.push(i);
}
s = null;
for (int i = n; i >= 1; i--)
{
while (!s.empty() && num[s.top()] < num[i])
{
rightn[i] = s.top(); s.pop();
}
s.push(i);
}
printf("Case %d:\n", k);
for (int i = 1; i <= n; i++)
{
cout << leftn[i] << " " << rightn[i] <<endl;
}
}
return 0;
}