poj 1068解题报告

大概题意为:

对于一段括号序列,有两种遍历方式

其中方式p为每遇到一个右括号就输出其前面有多少个左括号

方式w为每遇到一个右括号就输出在他和自己匹配的左括号之间有多少个右括号(包括自己)

现在给出序列p,要求求出对应的序列w

方法一:

先转换回真正的括号序列,用01表示,然后转换为w序列


//poj 1068
//260K 16MS 
#include <iostream>
using namespace std;

#define  MAX_LEN  1024
//p串形式转移为括号对01表示
int Psque2Bsque(int psLen, int *Psque, int *Wsque)
{
	int NowLoc = 0; //当前未赋值的位置
	int nowLeftPars = 0;
	int nextLeftPars = 0;
	for(int k = 0; k < psLen; k++)
	{
		nextLeftPars = Psque[k];
		int differ = nextLeftPars - nowLeftPars;
		if (differ > 0)
		{
			for (int i = 0; i< differ; i++)
			{
				Wsque[NowLoc] = 0;  //代表左括号
				NowLoc++;
			}
			nowLeftPars = nextLeftPars;
		}
		Wsque[NowLoc] = 1;  //放入对应的右括号
		NowLoc++;

	}
	return NowLoc;  //返回的括号总数
}

void Bsque2Wsque(int RealLen, int *Bsque, int *Wsque)
{
	int nWloc = 0;  //w串中现在的位置
	int pairs = 0;  //标记找到的括号是否成对
	int nBloc = 0;
	int nNum = 0;  //右括号个数
	for (int i = 0; i<RealLen; i++)
	{
		pairs = 1;
		nBloc = i;  //从这个位置开始向前找
		if (Bsque[i] == 1)  //如果是右括号
		{
			nNum = 1;
			while (pairs > 0)
			{
				nBloc--;
				if ( Bsque[nBloc]==0 )
				{
					pairs--;
				}
				else
				{
					pairs++;
					nNum++;
				}
			}
			Wsque[nWloc] = nNum;
			nWloc++;
		}
	}
}

int main()
{
	int nCaseNum = 0;
	int nStrLen = 0;  //输入串长
	int nReLen = 0;   //真实括号串长度
	int nInputStr[MAX_LEN] = {0};
	int nRezlSta[MAX_LEN] = {0};
	int nWsque[MAX_LEN] = {0};

	cin>>nCaseNum;
	while (nCaseNum-- > 0)
	{
		cin>>nStrLen;
		for (int i= 0; i< nStrLen; i++)
		{
			cin>>nInputStr[i];
		}

		nReLen = Psque2Bsque(nStrLen, nInputStr, nRezlSta);
		Bsque2Wsque(nReLen, nRezlSta, nWsque);

		for (int i = 0; i< nStrLen; i++)
		{
			cout<<nWsque[i]<<" ";
		}
		cout<<endl;
	}
	//system("pause");
	return 0;
}





方法二:

拿4 5 6 6 6 6 为例,可知第一个')' 前面有四个'(' ,按照栈的规则,说明第一个')'与第四个'(' 匹配,同理第二个 ')' 与 第五个 '(' 匹配,第三个')' 与第六个 '(' 匹配,在看第四个,由于第六个'('、第五个'('、第四个'('、已经被匹配,所以第四个')' 应该是和第三个'(' 匹配,以此类推。。。。用一个数组保存的匹配的结果(match[]),用一个标记数组并进行左查找,找到最左边那个没有匹配的左括号···

p序列:4 5 6 6 6 6       

匹配结果:4 5 6 3 2 1 

w序列为:1 1 1 4 5 6

再以 3 为例,因为在这个')'之前的第四个'('、五个'('、第六个'('已经被匹配,每一次匹配是一个')', 加上本身 所以结果应该是 6-3+1,以此类推结果就出来了。。。 ^_^

//248K 0MS 
#include <iostream>
using namespace std;

int main()
{
	int nCase = 0 ;
	int nInputNum;
	int nInput[21];
	int nMatch[21];
	int nMark[21];
	int loc = 0;
	
	cin>>nCase;
	while (nCase-- > 0)
	{
		cin>>nInputNum;
		memset(nMark, 0, sizeof(nMark));
		for (int i = 0; i< nInputNum; i++)
		{
			cin>>nInput[i];
			loc =nInput[i] ;
			while (nMark[loc] != 0)   //表示第i个左括号是否已经匹配
			{
				loc--;
			}
			nMatch[i] = loc;
			nMark[loc] = 1;
			cout<<nInput[i] - nMatch[i] + 1<<" ";
		}
		cout<<endl;
	}

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值