在 CODECHEF C++ 的 HELP BOB 问题中接受使用向量但拒绝使用数组
Accepted using Vectors but Rejected using Arrays in HELP BOB problem on CODECHEF C++
参考问题https://www.codechef.com/problems/HBOB02
在这个问题中,我使用下面的代码解决了它,但首先我使用数组而不是向量,但我得到了错误的答案。为什么这样????
#include <bits/stdc++.h>
#define mod 1000000007
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n,k;
cin>>n>>k;
k=k-1;
vector<long long>arr(n); //if i use long long arr[n] here the solution is not accepted
for(long long i=0;i<n;i++)
{
cin>>arr[i];
}
vector<long long>ar(n); //also changing long long ar[n] here
ar[0]=arr[0];
for(long long i=1;i<n;i++)
{
ar[i]=arr[i]^arr[i-1];
}
long long cnt=0;
for(long long i=0;i<n;i++)
{
if(ar[i]&(1<<k))
cnt++;
}
cout<<cnt;
return 0;
}
in>>n>>k;
vector<long long>arr(n); //if i use long long arr[n] here the solution is not accepted
数组变量的大小必须是 C++ 中的编译时常量值。出于显而易见的原因,在运行时从用户输入读取的值不是编译时常量值。因此,声明注释中建议的数组会使程序格式错误。
可变长度数组不是 C++ 标准的一部分,但一些编译器将它们作为扩展提供。如果它们变得太大,程序就会中断。
但是,您甚至不需要存储所有这些数字。
由于您显然热衷于“竞争性”编程,这里有一个解决方案,它只使用您的一小部分内存,并且执行三分之一的循环迭代。
int main()
{
unsigned int n, k;
cin >> n >> k;
k -= 1;
int cnt = 0;
unsigned int last = 0;
for(int i = 0; i < n; i++)
{
unsigned int next;
cin >> next;
cnt += ((next^last) >> k) & 1;
last = next;
}
cout << cnt;
}
参考问题https://www.codechef.com/problems/HBOB02
在这个问题中,我使用下面的代码解决了它,但首先我使用数组而不是向量,但我得到了错误的答案。为什么这样????
#include <bits/stdc++.h>
#define mod 1000000007
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n,k;
cin>>n>>k;
k=k-1;
vector<long long>arr(n); //if i use long long arr[n] here the solution is not accepted
for(long long i=0;i<n;i++)
{
cin>>arr[i];
}
vector<long long>ar(n); //also changing long long ar[n] here
ar[0]=arr[0];
for(long long i=1;i<n;i++)
{
ar[i]=arr[i]^arr[i-1];
}
long long cnt=0;
for(long long i=0;i<n;i++)
{
if(ar[i]&(1<<k))
cnt++;
}
cout<<cnt;
return 0;
}
in>>n>>k;
vector<long long>arr(n); //if i use long long arr[n] here the solution is not accepted
数组变量的大小必须是 C++ 中的编译时常量值。出于显而易见的原因,在运行时从用户输入读取的值不是编译时常量值。因此,声明注释中建议的数组会使程序格式错误。
可变长度数组不是 C++ 标准的一部分,但一些编译器将它们作为扩展提供。如果它们变得太大,程序就会中断。
但是,您甚至不需要存储所有这些数字。
由于您显然热衷于“竞争性”编程,这里有一个解决方案,它只使用您的一小部分内存,并且执行三分之一的循环迭代。
int main()
{
unsigned int n, k;
cin >> n >> k;
k -= 1;
int cnt = 0;
unsigned int last = 0;
for(int i = 0; i < n; i++)
{
unsigned int next;
cin >> next;
cnt += ((next^last) >> k) & 1;
last = next;
}
cout << cnt;
}