跳到正文

题解

题解:P17401 [ICPC 2018 Shenyang R] How Much Memory Your Code Is Using?

wyb666999约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年9月4日
收录
2026年9月5日
更新
2026年11月11日
篇幅
约 3 分钟
获赞
1
题目
P17401

版本

  1. v1当前

题解:P17401 [ICPC 2018 Shenyang R] How Much Memory Your Code Is Using?

题意

多组测试,每组输入n行,问这些变量一共占多少内存KIB

解答

我们可以累加所有变量的字节,但是题目问的是KIB,所以还要再除以1024并向上取整

下面是所有类型的字节

  • char →\to 1个字节
  • bool →\to 1个字节
  • int →\to 4个字节
  • long long →\to 8个字节
  • _int128 →\to 16个字节
  • float →\to 4个字节
  • double →\to 8个字节
  • long double →\to 16个字节

最后的代码

(就知道你们想看这个)

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

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int T;
    cin>>T;

    for (int tc=1; tc<=T; ++tc) {
        int n;
        cin>>n;

        long long tot=0;

        for (int i=0; i<n; ++i) {
            string typ, var;
            cin>>typ;

            if (typ=="long") {
                string nxt;
                cin>>nxt;
                typ+=" "+nxt;
                cin>>var;
            } else {
                cin>>var;
            }

            int sz=0;
            if (typ=="char"||typ=="bool") sz=1;
            else if (typ=="int"||typ=="float") sz=4;
            else if (typ=="long long"||typ=="double") sz=8;
            else if (typ=="__int128"||typ=="long double") sz=16;

            if (var.find('[')==string::npos) {
                tot+=sz;
            } else {
                int p=var.find('[');
                string num=var.substr(p+1);
                num.pop_back();
                if (num.back()==';') num.pop_back();
                long long cnt=stoll(num);
                tot+=sz*cnt;
            }
        }

        long long ans=(tot+1023)/1024;
        cout<<"Case #"<<tc<<": "<<ans<<"\n";
    }

    return 0;
}
原文