就是分割输入的内容,然后分辨到底申请了多少内存空间,虽然是水题没什么算法,但是对于输入的处理和编写代码的能力提升有一定的作用
我发现自己现在写的代码占有内存都是比较多的,因为我一开始接触到题目,思考如何去解决的时候总是在想一些如何在结构上面做文章,所以
虽然思路会因此变得简单得多,但是申请的内存不是太少,速度有待提高,总之,慢慢学会优化,慢慢才能写出高质量的代码啊
@--@ 加油!
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
#define max_n 301
int n;
typedef struct{
string type;
int size;
}type;
type m[max_n]={
{"int",4},{"float",4},{"bool",1},{"char",1},{"double",8}
};
int getsize(string type){
for(int i=0;i<5;i++){
if(m[i].type==type)
return m[i].size;
}
return 0;
}
int toint(string num){
int ans=0;
int l=num.size()-1;
num=num.substr(1,l);
l=num.size()-1;
for(int i=0;i<num.size();i++)
ans+=(num[i]-'0')*pow(10,l-i);
return ans;
}
int main()
{
while(cin>>n){
int memory=0;
//solve the n input case
string intype;
for(int i=0;i<n;i++){
int havearray=0;
//first input the type of ask memory
cin>>intype;
//then find the type's size is m[intype]
string arraysize="";
bool ok=false;
while(true){
//then input the poly
char ch;
cin>>ch;
if(ch==';'){
memory+=getsize(intype);
break;
}
if(ch==','){
memory+=getsize(intype);
}
if(ch==' ') continue;
if(ch=='[') ok=true;
if(ch==']')
{
ok=false;
memory+=toint(arraysize)*getsize(intype);
arraysize="";
havearray++;
}
if(ok){
arraysize+=ch;
}
}
//一个将字符串转换为数字的函数在这里需要
if(havearray){
memory-=getsize(intype)*havearray;
}
}
cout<<memory<<endl;
}
return 0;
}