Uint47 calculator
In the distant space, there is a technologically advanced planet.
One day they provided the Earth with a code that could achieve the ultimate meaning of the universe. People were very happy, but found that this code can only run on computers with a word length of 47 bits. As a good computer scientist, you need to implement a tool to simulate running this code on our computer.
This tool needs to simulate the following instructions:
"def x n" : define a unsigned 47 bits integer variable named x, with initial value n, n is an integer in [0, 2^47-1]
"add x y" : means x = x + y
"sub x y" : means x = x - y
"mul x y" : means x = x * y
"div x y" : means x = x / y, we guarantee y is not zero
"mod x y" : means x = x % y, we guarantee y is not zero
When the result of addition and multiplication cannot be represented by 47 bits, the part above 47 bits is truncated.
When the result of subtraction is less than zero, the result should add 2^47.
The name of each variable only contains letters and the length does not greater than 20.
Input
Contains multiple lines of input, one instruction per line.
Output
For each instruction, output the value of the first argument after calculation. For example, "def abc 100", then your output will be "abc = 100" in a line with no quotation marks.
See Sample Output for more information.
Sample Input
def six 6
def abc 1
def bcd 0
sub bcd abc
add abc six
def universe 0
mul abc six
add universe abc
div bcd six
mod bcd abc
Sample Output
six = 6
abc = 1
bcd = 0
bcd = 140737488355327
abc = 7
universe = 0
abc = 42
universe = 42
bcd = 23456248059221
bcd = 5
题意:
给出五中操作方式 分别为def、add、mul等 对def 后面跟字符串a 和数字x 表示给字符串权值为x 其余操作均是 后跟两字符串x、y 表两者间的各种运算 且所有字符串 前民已经用def定义了
思路:
map数组:
学过map的话 应该可以想到用它 但我之前学过 可没好好的用过 借这个机会好好学一下
开始写了结构体 先查然后计算 最后更新 总是WA 就听学长的用了map
map有个很好的特点 就是作用相当于数组
例如:a[3] 现在 定义了个map<string,int>mp 就可以用字符串或其他类型(其他类型要重新定义)来代替原来的3 并且数组大小无穷 不受限制
快速积:
第一次听说 因为在计算中出现2^47 * 2^47 很有可能会爆LL 这时候快速乘就有用处了 它可以实现边乘边取余
代码上和快速幂基本相同 差别是初始定义ans=0 还有把乘法改成加法就可以了 原理还没有好好的看
各种取余公式:
对于加法取余:(a+b)%mod=(a%mod+b%mod)%mod
乘法:(a*b)%mod=(a%mod*b%mod) %mod
减法:(a-b)%mod=(a-b+mod)%mod 这个地方一定要仔细 好多题都是卡这个
除法:估计要用到逆元
还有个小知识点就是:
求2的n次幂的时候 可以直接用 1LL<<n 表示 没必要写快速幂
AC代码:
#include<iostream>
#include<stdio.h>
#include<map>
#include<string>
using namespace std;
typedef long long LL;
LL mod=1LL<<47;
map<string,LL>mp;
LL qmul(LL a,LL b)
{
LL ans=0;
while(b){
if(b%2){
ans=(ans+a)%mod;
}
a=(a+a)%mod;
b/=2;
}
return ans;
}
int main()
{
string a,b,c;
while(cin>>a>>b){
LL num;
if(a=="def"){
cin>>num;
}
else{
cin>>c;
if(a=="add"){
num=(mp[b]+mp[c])%mod;
}
else if(a=="sub"){
num=(mp[b]-mp[c]+mod)%mod;
}
else if(a=="mul"){
num=qmul(mp[b],mp[c]);
}
else if(a=="div"){
num=mp[b]/mp[c];
}
else if(a=="mod"){
num=mp[b]%mp[c];
}
}
if(num<0){
num+=mod;
}
mp[b]=num;
cout<<b<<" = "<<num<<"
";
}
return 0;
}