#2019120500008-LG 数据结构 栈(1)

P1044 P1449 P1739 数据结构 栈

P1044 火车进站【模板 栈】

会TLE 所以\(n \leq 18\)\(14 \leq n \leq 18\)的数据本地跑完自动输出(骗分

#include <cstdio>
using namespace std;
const int N=50;
int out[N],n,tp,num,stk[N],ans=0;
void dfs(int x){
	int tmp,cat=0;
	if(x>n){
		ans++;
		while(tp){
			cat++,out[++num]=stk[tp--];
		}
		//for(int i=1;i<=n;i++){
		//	printf("%d",out[i]);
		//}
		//printf("\n");
		while(cat--){
			stk[++tp]=out[num--];
		}
		return ;
	}
	if(tp){
		tmp=stk[tp--];
		out[++num]=tmp;
		dfs(x);
		num--;
		stk[++tp]=tmp;
	}
	stk[++tp]=x;
	dfs(x+1);
	tp--;
} 
int ANS[20];
int main( ){
	ANS[14]=2674440;
	ANS[15]=9694845;
	ANS[16]=35357670;
	ANS[17]=129644790;
	ANS[18]=477638700;
	scanf("%d",&n);
	if(n>=14){
		printf("%d",ANS[n]);
		return 0;
	}
	dfs(1);
	printf("%d",ans);
	return 0;
}

P1449 后缀表达式

也叫逆波兰表达式
对于输入的序列,每两个数字和一个符号进行计算,返回一个数值替代这三个符号,直至最后栈中只剩下一个数

#include<iostream>
#include<cstdio>
using namespace std;
long long stk[1000];
int main(){
	long long i=0,now=0;
	char op;
    while((op=getchar())!='@'){
        if(op>='0'&&op<='9') now*=10,now+=op-'0';
        else if(op=='.'){
            stk[++i]=now;
            now=0;
        }
        else if(op=='+'){
            stk[i-1]=stk[i-1]+stk[i];
            stk[i]=0;
            i--;
        }
        else if(op=='-'){
            stk[i-1]=stk[i-1]-stk[i];
            stk[i]=0;
            i--;
        }
        else if(op=='*'){
            stk[i-1]=stk[i-1]*stk[i];
            stk[i]=0;
            i--;
        }
        else if(op=='/'){
            stk[i-1]=stk[i-1]/stk[i];
            stk[i]=0;
            i--;
        }
    }
    printf("%lld",stk[1]);
    return 0;
}

P1739 括号匹配

一开始不是按照栈写的,也能过

本质上是栈

#include <cstring>
#include <cstdio>
using namespace std;
char s[260]; 
int left=0,right=0,ok=0;
int main(){
	scanf("%s",s+1);
	int i=1;
	while(s[i]!='@'){
		if(s[1]==')') {
			printf("NO");
			return 0;
		}
		if(s[i]=='(') ok++;
		if(s[i]==')') ok--;
		//if(s[i]==')'&&left==0) right++;
		//if(s[i]==')'&&left!=0) left--;
		if (ok<0) {
			printf ("NO");
			return 0;
		}
        
		i++;
	}
	if (s[i]=='@') {
			if (!ok) printf("YES");
			else printf("NO");
			return 0;
		}
	//if(left!=0) printf("NO");
	//else printf("YES");
	return 0;
}
posted @ 2019-12-05 22:07  刘子闻  阅读(123)  评论(0编辑  收藏  举报