求CSP-ST2正解
  • 板块灌水区
  • 楼主yinbe
  • 当前回复4
  • 已保存回复4
  • 发布时间2023/10/28 13:57
  • 上次更新2023/11/2 11:05:29
查看原帖
求CSP-ST2正解
759152
yinbe楼主2023/10/28 13:57

我写了个O(n2)O(n^2)的暴力拿了50,教练要我们将这份代码优化成O(n)O(n)过掉这题,请问如何优化?

#include<iostream>
#include<stack>
using namespace std;
int n,cnt,ans,T;
string s;
stack<char>st;
int main()
{
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d",&n);
		cin>>s;
		for(int l=0;l<n;l++)
		{
			while(!st.empty())
			{
				st.pop();
			}	
			cnt=0;	
			st.push(s[l]);
			for(int r=l+1;r<n;r++)
			{
				if(st.empty())
				{
					cnt++;				
					st.push(s[r]);
					continue;
				}
				if(st.top()==s[r])
				{
					st.pop();
					if(st.empty()&&r==n-1)
					{
						cnt++;
					}				
				}
				else
				{
					st.push(s[r]);
				}
			}
			ans+=cnt;
		}
		printf("%d",ans);		
	}
	return 0;
}
2023/10/28 13:57
加载中...