题目连接:http://115.28.203.224/problem.php?cid=1012&pid=6
因为题目要求,运算符只有+和*,所以,不需用栈或队列也能做出。
将数字和字母分别存到两个数组中,存字母好想,本题关键就是要想到如何存数字!
代码实现:
#include<iostream>
#include<stdio.h>
#include<cstdio>
#include<string.h>
#include<cstring>
#include<string>
#include<queue>
#include<malloc.h>//头文件包含malloc函数,用来申请内存空间
#include<algorithm>
#include<math.h>
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');//加上sum*10是两位及两位以上的数字
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;//其余的都赋值为0
}
}
for (int l = 0; l < k; l++)
ans += s[l];
printf("%d\n", ans);
}
return 0;
}
学长用队列做的:
#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;
}