两解决方案。
注意把数组开大点,能装下10000个元素是保险的。
(1)
#include<stdio.h>
#include<string.h>
const int maxn=10000;
char s[maxn*3];
int A[maxn],stack[maxn],top,n;
int is_ok()
{
int i;
top=0;
for(i=0;i<n;i++)
{
if(A[i]<0) stack[++top]=A[i];
else if(top && stack[top]==-A[i]) top--;
else return 0;
}
if(top) return 0;
int sum=0,x=0;
for(i=0;i<n;i++)
{
if(A[i]<0) x++;
else x--;
if(x==0) sum++;
}
if(sum!=1) return 0;
for(i=0;i<n;i++)
if(A[i]<0)
{
int j;
int x=0;
for(j=i;;j++)
{
if(A[j]<0) x++;
else x--;
if(x==0) break;
}
int p=i+1,q=j-1;
int sum=0;
for(j=p;j<=q;j++)
{
if(A[j]<0) x++;
else x--;
if(x==0) sum+=A[j];
}
if(sum>=-A[i]) return 0;
}
return 1;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("11111.txt","r",stdin);
//freopen("in.txt","r",stdin);
#endif
while(fgets(s,sizeof(s),stdin)!=NULL)
{
//printf("%d\n",strlen(s));
memset(A,0,sizeof(A));
char token[]=" ";
char *p=strtok(s,token);
n=0;
while(p!=NULL)
{
if(sscanf(p,"%d",&A[n])==1) n++;
p=strtok(NULL,token);
}
if(is_ok()) printf(":-) Matrioshka!\n");
else printf(":-( Try again.\n");
}
return 0;
}
(2)
#include<stdio.h>
#include<string.h>
const int maxn=10000;
char s[maxn*3];
int A[maxn],B[maxn],C[maxn],b_top,c_top,n;
int is_ok()
{
b_top=0,c_top=0;
for(int i=0;i<n;i++)
if(A[i]<0)
{
B[++b_top]=A[i];
C[++c_top]=A[i];
}
else if(b_top && B[b_top]+A[i]==0)
{
b_top--;
c_top--;
if(b_top)
{
int m=C[c_top--];
m+=A[i];
if(m>=0) return 0;
C[++c_top]=m;
}
else if(i+1<n) return 0;
}else return 0;
return !b_top;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("11111.txt","r",stdin);
//freopen("in.txt","r",stdin);
#endif
while(fgets(s,sizeof(s),stdin)!=NULL)
{
memset(A,0,sizeof(A));
char token[]=" ";
char *p=strtok(s,token);
n=0;
while(p!=NULL)
{
if(sscanf(p,"%d",&A[n])==1) n++;
p=strtok(NULL,token);
}
if(is_ok()) printf(":-) Matrioshka!\n");
else printf(":-( Try again.\n");
}
return 0;
}
效率上,2比1好。