【牛客网】2019多校训练(1)A Equivalent Prefixes

题目链接:https://ac.nowcoder.com/acm/contest/881/A

题意:找到最大的p,使1~p的所有子区间的最小值下标相同。(刚开始的时候读错题目了)

题解:利用单调栈找到以当前数字所能延申的最长左右区间,当区间不相等的时候,即是答案。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
int a[maxn], b[maxn];
stack<int > sta1, sta2;
int main()
{
	int n, ans;
	while (cin >> n)
	{
		ans = 0;
		for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
		for (int i = 1; i <= n; i++) scanf("%d", &b[i]);
		for (int i = 1; i <= n; i++)//利用单调栈找左边能延申的最大长度,直到不相等。
		{
			int temp1, temp2;
			while (!sta1.empty() && a[sta1.top()] > a[i])    sta1.pop();
			while (!sta2.empty() && b[sta2.top()] > b[i])    sta2.pop();
			if (sta1.empty())   temp1 = 0;
			else    temp1 = sta1.top();
			if (sta2.empty())   temp2 = 0;
			else    temp2 = sta2.top();
			if (temp1 == temp2) ans++;
			else    break;
			sta1.push(i);
			sta2.push(i);
		}
		while (!sta1.empty())   sta1.pop();
		while (!sta2.empty())   sta2.pop();
		for (int i = ans; i >= 1; i--)//利用单调栈找右边能延申的最大长度,并且不断缩短右区间。
		{
			int temp1, temp2;
			while (!sta1.empty() && a[sta1.top()] > a[i])    sta1.pop();
			while (!sta2.empty() && b[sta2.top()] > b[i])    sta2.pop();
			if (sta1.empty())   temp1 = ans;
			else    temp1 = sta1.top() - 1;
			if (sta2.empty())   temp2 = ans;
			else    temp2 = sta2.top() - 1;
			if (temp1 != temp2)
				ans = min(temp1, temp2);
			sta1.push(i);
			sta2.push(i);
		}
		while (!sta1.empty())   sta1.pop();
		while (!sta2.empty())   sta2.pop();
		cout << ans << endl;
	}
	return 0;
}

优化:其实,可以发现只需要保证数字向左所能延申的区间相等即可。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
int a[maxn], b[maxn];
stack<int > sta1, sta2;
int main()
{
	int n, ans;
	while (cin >> n)
	{
		ans = 0;
		while (!sta1.empty())   sta1.pop();
		while (!sta2.empty())   sta2.pop();
		for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
		for (int i = 1; i <= n; i++) scanf("%d", &b[i]);
		for (int i = 1; i <= n; i++)//利用单调栈找左边能延申的最大长度,直到不相等。
		{
			int temp1, temp2;
			while (!sta1.empty() && a[sta1.top()] > a[i])    sta1.pop();
			while (!sta2.empty() && b[sta2.top()] > b[i])    sta2.pop();
			if (sta1.empty())   temp1 = 0;
			else    temp1 = sta1.top();
			if (sta2.empty())   temp2 = 0;
			else    temp2 = sta2.top();
			if (temp1 == temp2) ans++;
			else    break;
			sta1.push(i);
			sta2.push(i);
		}
		cout << ans << endl;
	}
	return 0;
}
发布了119 篇原创文章 · 获赞 20 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_40727946/article/details/96479645
今日推荐