ZOJ 3829 Known Notation

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liufengwei1/article/details/84495524

搞一手波兰表达式。

显然的策略:1.数字个数cnt必须大于等于*的个数数opt+1,cnt=opt+1时,前面放2个数字,后面*和数字交替放,这是极限了。

2.如果当前扫到的*号太多导致前面没数字可算了,我们从尽可能后面的地方找数字和它交换,因为数字越前面越好,*号越后面越好,合法的可能性更大

所以就记录一个当前前面的数字个数res,以及从后往前的指针numind,来从后往前找数字,因为每次交换要交换尽可能后面的数字。复杂度就是O(n)的了。

#include<bits/stdc++.h>
#define maxl 1010

using namespace std;

int n,opt,cnt,ans;
char s[maxl];

inline void prework()
{
	scanf("%s",s+1);
	n=strlen(s+1);
	opt=0;cnt=0;
	for(int i=1;i<=n;i++)
	if(s[i]=='*')
		opt++;
	else
		cnt++;
}

inline void mainwork()
{
	int res;
	if(opt+1>cnt)
		ans=opt+1-cnt,res=opt+1-cnt;
	else
		ans=0,res=0;
	int numind=n;
	for(int i=1;i<=n;i++)
	if(s[i]=='*')
	{
		if(res>1)
			res--;
		else
		{
			while(s[numind]=='*')
				numind--;
			swap(s[numind],s[i]);
			numind--;
			res++;ans++;
		}
	}
	else
		res++;
		
}

inline void print()
{
	printf("%d\n",ans);
}

int main()
{
	int t;
	scanf("%d",&t);
	for(int i=1;i<=t;i++)
	{
		prework();
		mainwork();
		print();
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/liufengwei1/article/details/84495524
ZOJ