欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > static 容器导致的WA

static 容器导致的WA

2025/4/30 20:32:54 来源:https://blog.csdn.net/MengYiKeNan/article/details/144154578  浏览:    关键词:static 容器导致的WA

问题:

在做力扣3337. 字符串转换后的长度 II的时候提交提示wrong answer,然后不进行任何修改的情况下把错误样例在本地运行一下发现是正确的。

原因:

经过测试发现是静态数据结构的问题。

由于SIZE是静态常量,所以array<int, SIZE>定义出来的变量也是静态的。

解决:

如果需要用array<int, SIZE>来定义变量可以在变量名之后添加{},如array<int, SIZE> cnt{};这样就算cnt是静态的,每次运行这段代码时也会直接清空里边的数据。

原来的代码:

class Solution {static constexpr int SIZE = 26;static constexpr int MOD = 1e9 + 7;using Matrix = array<array<int, SIZE>, SIZE>;using LL = long long;Matrix mul(Matrix& a, Matrix& b) {Matrix c{};for (int i = 0; i < SIZE; ++ i) {for (int j = 0; j < SIZE; ++ j) {for (int k = 0; k < SIZE; ++ k) {c[i][j] = (c[i][j] + (LL) a[i][k] * b[k][j]) % MOD;}}}return c;}Matrix pos(Matrix a, int n) {Matrix res{};for (int i = 0; i < SIZE; ++ i) {res[i][i] = 1;}while (n) {if (n & 1) {res = mul(res, a);}a = mul(a, a);n >>= 1;}return res;}public:int lengthAfterTransformations(string s, int t, vector<int>& nums) {Matrix m{};for (int i = 0; i < SIZE; ++ i) {for (int j = i + 1; j <= i + nums[i]; ++ j) {m[i][j % SIZE] = 1;}}m = pos(m, t);array<int, SIZE> cnt;for (char c : s) {cnt[c - 'a'] += 1;}long long ans = 0;for (int i = 0; i < SIZE; ++ i) {ans += reduce(m[i].begin(), m[i].end(), 0LL) * cnt[i];}return ans % MOD;}
};

正确的代码:

class Solution {static constexpr int SIZE = 26;static constexpr int MOD = 1e9 + 7;using Matrix = array<array<int, SIZE>, SIZE>;using LL = long long;Matrix mul(Matrix& a, Matrix& b) {Matrix c{};for (int i = 0; i < SIZE; ++ i) {for (int j = 0; j < SIZE; ++ j) {for (int k = 0; k < SIZE; ++ k) {c[i][j] = (c[i][j] + (LL) a[i][k] * b[k][j]) % MOD;}}}return c;}Matrix pos(Matrix a, int n) {Matrix res{};for (int i = 0; i < SIZE; ++ i) {res[i][i] = 1;}while (n) {if (n & 1) {res = mul(res, a);}a = mul(a, a);n >>= 1;}return res;}public:int lengthAfterTransformations(string s, int t, vector<int>& nums) {Matrix m{};for (int i = 0; i < SIZE; ++ i) {for (int j = i + 1; j <= i + nums[i]; ++ j) {m[i][j % SIZE] = 1;}}m = pos(m, t);array<int, SIZE> cnt{};for (char c : s) {cnt[c - 'a'] += 1;}long long ans = 0;for (int i = 0; i < SIZE; ++ i) {ans += reduce(m[i].begin(), m[i].end(), 0LL) * cnt[i];}return ans % MOD;}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词