首页 > 解决方案 > 在 CODECHEF C++ 上的 HELP BOB 问题中接受使用向量,但拒绝使用数组

问题描述

参考问题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;
}

标签: c++arraysvectorbit-manipulation

解决方案


可变长度数组不是 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;
}

推荐阅读