题目不难,但有一个很大的意外的收获。
问题:当maxn定义为1024 + 10时,会run error,此时把s定义为全局变量时,AC。
结论:
这里1024 + 10本身定义小了,而由于其被定义为全局变量,恰巧对了。编译器下,即便越出了数组本身的界限,但没有非法访问,不会报错,没有任何问题。全局变量所在的堆空间比较大,较局部变量所在的栈域来说,更不易造成非法访问。
#include<bits/stdc++.h> using namespace std; const int len = 32; const int maxn = 2048 + 30; int buf[len][len]; int cnt; //将s[p...]画到以(r,c)为左上角,宽度为w的画布上 void draw(const char* s, int& p, int r, int c, int w) { char ch = s[p++]; if(ch == ‘p‘){ draw(s, p, r, c + w/2, w/2); //右上 draw(s, p, r, c, w/2); //左上 draw(s, p, r + w/2, c, w/2); //左下 draw(s, p, r + w/2, c + w/2, w/2); //右下 }else if(ch == ‘f‘){ for(int i = r; i < r + w; i++){ for(int j = c; j < c + w; j++){ if(buf[i][j] == 0){ buf[i][j] = 1; cnt++; } } } } } int main() { int T; scanf("%d", &T); while(T--){ char s[maxn]; memset(buf, 0, sizeof(buf)); cnt = 0; for(int i = 0; i < 2; i++){ scanf("%s", s); int p = 0; draw(s, p, 0, 0, len); } printf("There are %d black pixels.\n", cnt); } return 0; }
原文:https://www.cnblogs.com/sanshi-2018/p/10408112.html