OUTOJ 简单的计算式(普通方法+队列法)

这篇博客介绍了如何解决 OUTOJ 上的一个计算式问题,该问题涉及加法和乘法操作。作者指出,虽然通常这类问题需要使用栈或队列,但在这个特定案例中,可以通过不依赖数据结构的方式来解决。文章提供了两种解题思路,一种是常规方法,另一种是利用队列来处理数字。并附带了相关代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目连接: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;  
    }  



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值