码蹄杯 消除小球 题型:栈

56 阅读1分钟

码题集OJ-消除小球 (matiji.net)

image.png

输入样例

5 2
abbab

输出样例

b

输入样例

6 3
aabbba

输出样例

>_<

样例解析

我们读入一个长度为n的字符串s,遍历这个字符串,每次看s[i]是否和栈顶元素的颜色是否一样,并且看栈顶元素的cnt是否为k-1,如果是,那么就可以把栈内k-1个元素出栈:

image.png

code

#include<bits/stdc++.h>

using namespace std;
stack<char>ans;
struct NODE
{
  char color;
  int cnt;	
};
void solve()
{
	int n,k;cin>>n>>k;
	string s;cin>>s;
 	stack<NODE> st; 
    
    for(int i=0;i<n;i++)
    {
       if(st.size()!=0 && st.top().color==s[i])
       {
       	if(st.top().cnt==k-1)
       	{
       		for(int j=1;j<=k-1;j++)
       		{
       			st.pop();   
			}
	    }
	    else
	    {
	       st.push({s[i],st.top().cnt+1});
		}
	   }	    
	   else
	   {
	     st.push({s[i],1}); 
	   }
	}
	
	

	int sz=st.size();
	if(sz==0) cout<<">_<"<<endl;
	else
	{
		for(int i=1;i<=sz;i++)
		{
			ans.push(st.top().color);
			st.pop();
		}
	}
	for(int i=1;i<=sz;i++)
	{
		cout<<ans.top();ans.pop();
	}
}
int main()
{
  int t=1;
  while(t--)
  {
  	solve();
  }
  
 return 0;	
}