计蒜客 合并数字 (思维 + 栈)

传送门

思路:

    大力vector搞T了一个点。。。。

       这个题其实应该注意到是最左面相邻的绝对值相差为1的。那么这里可以用个栈,显然栈里存的都是不满足相邻为差的,对于新来的一个值,由于要满足最左面,栈里又是都不满足的,所以肯定是和栈顶比较是否满足条件了,满足就保留小的继续和栈顶判断,一直到不满足为止。

#include <bits/stdc++.h>

using namespace std;
const int maxn = 1e5+5;
stack<int>st;
int n;
int main()
{
	while(~scanf("%d",&n))
	{
		while(!st.empty()) st.pop();
		int cnt = 0;
		for(int i = 1;i <= n;++i)
		{
			int x;
			scanf("%d",&x);
			if(st.empty())
			st.push(x);
			else
			{
				while(!st.empty())
				{
					int tmp = st.top();
					if(abs(tmp - x) != 1)
					{
						st.push(x);
						break;
					}
					else
					{
						cnt++;
						if(tmp > x)
						st.pop();
						else
						break;
					}
				}
				if(st.empty())
					st.push(x);
			}
		}
		cout << cnt << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/howardemily/article/details/79763432