点击打开链接 一个嵌套玩具由一个非空不包含0的序列表示,每一对数-k,k表示一个玩具的尺寸,并且负数出现在前,并且外层玩具要大于其内层玩具尺寸之和,比如 -9 -7 -2 2 -3 -1 -2 2 1 3 7 9 9包含7,7包含 2和3,3 包含 1 和2 但是1 不能包含 2 所以出错。 现在需要判断一个序列是否合法。一个序列合法就是外层的必须大于其内层的和,并且需要正确嵌套,不存在单个的情况。 用两个栈来存储,一个用来存储当前序列,一个用来存储当前这一层还能包含多大尺寸的娃娃。 <span style="color:#000000;">#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <cstring>
#include <string>
#include <algorithm>
#include <string>
#include <set>
#include <functional>
#include <numeric>
#include <sstream>
#include <stack>
#include <map>
#include <queue>
#define CL(arr, val) memset(arr, val, sizeof(arr))
#define ll long long
#define inf 0x7f7f7f7f
#define lc l,m,rt<<1
#define rc m + 1,r,rt<<1|1
#define pi acos(-1.0)
#define L(x) (x) << 1
#define R(x) (x) << 1 | 1
#define MID(l, r) (l + r) >> 1
#define Min(x, y) (x) < (y) ? (x) : (y)
#define Max(x, y) (x) < (y) ? (y) : (x)
#define E(x) (1 << (x))
#define iabs(x) (x) < 0 ? -(x) : (x)
#define OUT(x) printf("%I64d\n", x)
#define lowbit(x) (x)&(-x)
#define Read() freopen("a.txt", "r", stdin)
#define Write() freopen("dout.txt", "w", stdout);
#define N 100005
using namespace std;
int f[10000],n;
bool solve()
{
stack<int>s,sum;
for(int i=0;i<n;i++)
{
if(f[i]<0) //小于0就压栈
{
if(s.size()>=1)
{
if(sum.top()<=abs(f[i])) return false; //内层玩具的尺寸大于外层 返回错误
int temp=sum.top();
temp-=abs(f[i]); //减去内层的尺寸,表示内层还能容纳这么大的娃娃
sum.pop();sum.push(temp);
}
s.push(f[i]);
sum.push(abs(f[i])); //新的一层
}
else
{
if(s.empty()) return false; //不匹配
if(abs(s.top())!=f[i]) return false; //不匹配
s.pop(); //匹配成功
sum.pop();
}
}
return true;
}
int main()
{
// Read();
int a;
char c;
n=0;
while(~scanf("%d%c",&a,&c))
{
f[n++]=a;
if(c=='\n')
{
if(n%2) printf(":-( Try again.\n"); //奇数个 数
else
{
bool flag=solve();
if(flag) printf(":-) Matrioshka!\n");
else printf(":-( Try again.\n");
}
n=0;
}
}
return 0;
}
</span> |