POJ-1068题

下面的代码是北京大学Online Judge网站上1068题(网址:http://poj.org/problem?id=1068)的所写的代码。

该题的难点在于实现括号匹配,我在代码中采取用-1和1分别代表左右括号,使得括号匹配时各位数相加为0,不匹配时则不为0的方法来判断是否完成括号匹配,代码列表如下:

性能:Memory:704K,Time:0MS

#include "iostream"
using namespace std;
int main()
{
const int LEFT_PARA = -1;//左括号为-1
const int RIGHT_PARA = 1;//右括号为1
int nProblem;//问题个数
int n;
int S[40];
int P[20];
int W[20]; //ifstream cin("input_data.txt",ios::in);//便于读取输入文件
cin>>nProblem;
while (nProblem--)
{
cin>>n;
for (int i=0;i<n;i++)
{
cin>>P[i];
} //生成S
for (int j = 0,k=0;j<n;j++)
{
if (j == 0)
{
for (k=0;k<P[j];k++)
{
S[k] = LEFT_PARA;
}
S[k] = RIGHT_PARA;
}else{
int m;
for (m = k+1;m<k+1+P[j]-P[j-1];m++)
{
S[m] = LEFT_PARA;
}
S[m] = RIGHT_PARA;
k = m;
}
} //生成W
for (int j=0;j<n;j++)
{
W[j] = 0;
}
for (int j = 0,k=0,m=0;j<2*n;j++)
{
int tempSum = 0;
if (S[j] == RIGHT_PARA)
{ for (int k = j;k>=0;k--)
{ if (S[k] == RIGHT_PARA)
{
W[m] += 1;
}
tempSum += S[k];
if (tempSum == 0)
{
cout<<W[m]<<" ";
m++;
break;
}
} }
}
cout<<endl;
}
return 0;
}

  

上一篇:Go语言中多字节字符的处理


下一篇:ubuntu qq