蓝桥杯2022国赛A组 内存空间(字符串操作)

蓝桥杯2022国赛A组

III. 内存空间

string.rfind("some_string_or_char", [pos]):从下标为pos开始逆向查找,正向匹配。若找到,返回(正向开始计数的)下标;若结果找不到,返回npos.

getline(in, temp, [delim]):从输入流in(cin / stringstream等)读取字符,temp变量用来存储字符,delim是结束标志,默认为换行符,读到EOF时也会终止,delim会被读取并丢弃。

#include <bits/stdc++.h>
using namespace std;

typedef long long LL;
int weight;
LL sum = 0;

void modify(long long weight, string s){
    // 非数组
    if(s.find("[") == -1) sum += (count(s.begin(), s.end(), ',') + 1) * weight;
    // 数组
    else{
        stringstream ss(s);
        string token;
        vector<string> tokens;
        while (getline(ss, token, ',')) tokens.push_back(token);
        string str;
        for (auto t : tokens) {
            for(int i = t.size() - 1; i >= 0; i --)
                //找到数组位置 
                if(t[i] == '[') {
                    //找到数组结束位置 
                    str = t.substr(i + 1, t.rfind(']') - i - 1); 
                    sum += stoi(str) * weight;
                    break;
                }
        }
    }
}

void modifystr(string s){
    stringstream ss(s);
    string token;
    vector<string> tokens;
    while(getline(ss, token, ',')) tokens.push_back(token);
    string str;
    for(auto& t : tokens) {
        int flag = 0, cnt = 0;
        for(int i = 0; i <= (int)t.size() - 1; i ++) {
            //找到引号标记为找到了第一个引号, 
            if(t[i] == '"') {
                flag ++;
                if(flag == 2) break;
                continue;
            }
            //没找到引号的时候 
            if(flag == 1) cnt ++;
        }
        //算出贡献值 
        sum += cnt;
    }    
}

int main(){
    int t;
    cin >> t; 
    cin.get(); //获取第一个回车符
    while(t --) {
        string s;
        getline(cin, s);
        if(s.substr(0, 3) == "int") modify(4, s);
        else if(s.substr(0, 4) == "long") modify(8,s); 
        else if(s.substr(0, 6) == "String") modifystr(s);
    }
    int a = sum / 1024 / 1024 / 1024;
    int b = sum / 1024 / 1024 % 1024;
    int c = sum / 1024 % 1024;
    int d = sum % 1024;
    if(a != 0) cout << a << "GB";
    if(b != 0) cout << b << "MB";
    if(c != 0) cout << c << "KB";
    if(d != 0) cout << d << "B";
    return 0;
}