链接:http://115.28.203.224/problem.php?cid=1012&pid=6
G: 简单的计算式
时间限制: 1 Sec 内存限制: 128 MB提交: 38 解决: 7
题目描述
给你一个表达式,式子只有加号和乘号,让你输出结果。
输入
第一行输入一个T,代表T组数据。(输入保证没有多余空格)
接着T行,每行一个字符串,代表一个表达式(只含有+ *)
字符串长度<=1000
输出
对应每行输出一个结果。
样例输入
2
1+3*3+4
4*3*5+8
样例输出
14
68
提示
结果保证在int范围内。
思路:比赛题,很简单,把数字和字符分到两个数组中计算
比完赛想到了栈,如果有除法的话确实需要栈,但是加乘不需要了~
代码:
#include <iostream>
#include<stdlib.h>>
#include<stdio.h>
#include<cmath>
#include<string>
#include<string.h>
#include<queue>
#include<stack>>
using namespace std;
const int maxn = 10000+10;
const int INF = 1e9;
int n;
char str[maxn];
int s[maxn];
char ch[maxn];
int k;
int j;
void init(){
int len = strlen(str);
int sum = 0;
k = 0;
j = 0;
for(int i = 0;i<len;i++){
if(str[i]>='0'&&str[i]<='9'){
sum = sum*10+(str[i]-'0');
if(str[i+1]<'0' || str[i+1]>'9'){
s[k] = sum;
k++;
sum = 0;
}
}
else {
ch[j] = str[i];
j++;
}
}
}
int main(){
scanf("%d",&n);
while(n--){
int ans = 0;
scanf("%s",str);
init();
for(int l = 0;l<j;l++){
if(ch[l]=='*') {
s[l+1] = s[l]*s[l+1];
s[l] = 0;
}
}
for(int l = 0;l<k;l++)
ans +=s[l];
printf("%d\n",ans);
}
}
石万东学长的队列代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#define inf 0x3f3f3f3f
#define met(a,b) memset(a,b,sizeof a)
#define pb push_back
typedef long long ll;
using namespace std;
const int N = 1050;
const int M = 24005;
const int mod=1e9+7;
int n,m;
int a[N][N];
int main() {
int t;
stack<ll>q;
scanf("%d",&t);
while(t--){
while(!q.empty())q.pop();
char str[1008];
scanf("%s",str);
ll now=0,t=1;
for(int i=0;i<strlen(str);i++){
if(str[i]>='0'&&str[i]<='9'){
now=now*10+str[i]-'0';
}
else if(str[i]=='+')q.push(t*now),now=0,t=1;
else if(str[i]=='*'){
t*=now;
now=0;
}
}
q.push(t*now);
ll ans=0;
while(!q.empty()){
ans+=q.top();q.pop();
}
printf("%lld\n",ans);
}
return 0;
}