代码不开O2就对了?

P4387 【深基15.习9】验证栈序列

cat_lover1 @ 2023-10-09 21:29:16

原题地址

事情是这样的,这道题开O2就错,不开O2就对

代码如下

#define G getchar()
static inline int r(){
  int i=0,c;
  while((c=G)<48);
  for(;c>47;c=G)i=(i<<1)+(i<<3)+(c^48);
  return i;
}main(){
  int q=r();
  while(q--){
    int n=r();
    int s[n+1],p[n+1],t[n+1],top=-1,x=0,q=0;
    s[n]=p[n]=t[n]=-1;
    for(int i=0;i<n;++i)s[i]=r();
    for(int i=0;i<n;++i)p[i]=r();
    while(q<n&&x<n){
      if(top==-1)t[++top]=s[x++];
      while(p[q]!=t[top])t[++top]=s[x++];
      while(p[q]==t[top])--top,++q;
    }
    if(q<n)puts("No");
    else puts("Yes");
  }
}

by cat_lover1 @ 2023-10-09 21:30:57

提交记录,4RE1AC,开O2

提交记录5AC(不开O2)


by kevin4 @ 2023-10-09 21:32:41

你的代码可能有UB


by kevin4 @ 2023-10-09 21:35:37

https://www.luogu.com.cn/blog/StudyingFather/undefined-behavior

洛谷日报#265


by zzr1208 @ 2023-10-09 21:38:23

O2优化原理的事,但主要是你的程序有bug


by cat_lover1 @ 2023-10-09 21:38:46

@kevin4 感谢大佬指点,我明白了,我数组开小了


by cat_lover1 @ 2023-10-09 21:39:16

@zzr1208 感谢大佬


by zzr1208 @ 2023-10-09 21:41:46

话说C的main要不要return 0? @cz_awa 我觉得是return 0的事O2挂了


by zzr1208 @ 2023-10-09 21:42:32

不写返回值开O2就挂


by cat_lover1 @ 2023-10-09 21:44:19

@zzr1208 @kevin4 感谢大佬指点,但似乎不是返回值的问题,我很疑惑,我觉得数组也没用越界

AC记录(改进版)


by zzr1208 @ 2023-10-09 21:45:08

OK 但你改了什么


| 下一页