通读getchar_unlocked失败案例

Reading through getchar_unlocked -failed case

本文关键字:失败 案例 unlocked getchar 通读      更新时间:2023-10-16

这是我计算 no. 乘以 A[i]>B[j] 的代码,这样,我<·

 #include<iostream>
 #include<cstring>
 using namespace std;
 int main()
  {
  int n,c=0,j=1,i;
  cin>>n;
  int*a,*b;
  a=(int*)malloc(sizeof(int)*n);
  b=( int*)malloc(sizeof( int)*n);
  for( i=0;i<n;i++)
   {
    cin>>a[i];
   }
  for( i=0;i<n;i++)
  {
    cin>>b[i];
  }
  while(j<n)
   {
    for( i=0;i<j;i++)
    {
    if(a[i]>b[j])
    c++;
    }
  j++;
  }
 cout<<c;
return 0;
}

这很好用,我尝试使用getchar_unlocked来减少时间,但我在网站上得到了错误的答案。最初的测试用例向我展示了正确的输出,我确实使用输入流对所有情况进行了相同的算法工作cin但我未能使用 getchar_unlocked 我的输入函数中是否有任何错误,或者我在哪里做错了?

我的getchar_unlock看起来像这样

int readInt()
 {
  char c=getchar_unlocked();
  while(c<'1'||c>'9')
  c=getchar_unlocked();
  int ret=0;
  while(c>='1'&&c<='9')
  {
    ret=ret*10+c-48;
    c=getchar_unlocked();
  }
  return ret;
}

PS:我不知道失败的测试用例:(

如果存在非前导零,您的readInt()不起作用。例如,如果输入为 10 ,则将返回 1

这是我久经考验的实现(仅适用于非负整数)。

int get() {
    int res = 0;
    int c;
    do {
        c = getchar_unlocked();
    } while (c <= 32);
    do {
        res = 10*res + c - '0';
        c = getchar_unlocked();
    } while (c > 32);
    return res;
}

此外,我建议使用std::vector而不是直接调用mallocnew