HDU 3347 Calculate the expression(模拟 + map)

本文分享了一道通过暴力模拟解决的问题,重点介绍了如何使用C++中的map进行字符串到整数的映射,并通过快速幂函数提高效率。文章还提到了一些在实现过程中遇到的小技巧及注意事项。

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

思路:

总之很搞笑了,比赛时看看就跳过了的题到最后竟然是暴力模拟。
看到的第一眼就感觉是用map将字符串和int做一个映射,然而由于对map,string的恐惧让我一直没有付诸行动。现在想想,策略还是得改进一下:先T再说。。。
就当成一个对map运用方法的复习吧。。
注意没有一元运算符
ps:vj的题目略坑啊,乱码显示的搞的我没注意到还能试减号。。。(拼命给自己找理由)
ps:qp是quick_power,快速幂,顺手就写上了。

#include <iostream>
#include <cstdio>
#include <string.h>
#include <queue>
#include <cmath>
#include <algorithm>
#include <map>

typedef long long int lli;
using namespace std;

lli qp(lli a,lli b){
    lli res = 1;
    for(;b;b>>=1){
        if(b&1)
            res = res * a;
        a = a*a;
    }
    return res;
}
int ff(const string& a){
    int len = a.size();
    int ans = 0;
    for(int i = len-1;i >= 1;i--){
        ans += ( a[i]-'0' ) * qp(10,len - i-1);
    }
    if(a[0] == '-'){
        ans = -ans;
    }
    else{
        ans += ( a[0]-'0' ) * qp(10,len - 1);
    }
    return ans;
}

int main(){
    int t;
    cin>>t;
    int n;
    int temp;

    while(t--){
        scanf("%d",&n);
        map<string,int> ma;
        string a,b;
        for(int i = 1; i < n;i++){
            cin>>a>>b>>temp;
            ma[a] = temp;
        }
        lli res = 0;
        int fuhao = 1;
        while(1){
            cin>>a;
            if(a == "?")
                break;
            if(a == "+" || a == "="){
                fuhao = 1;
                continue;
            }
            else if(a[0] <= 'z' && a[0] >= 'a'){
                res += ma[a] * fuhao;
            }
            else if(a == "-"){
                fuhao = -1;
            }
            else{
                res += ff(a) * fuhao;
            }
        }
        printf("%lld\n",res);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值