如何解决异或相等codechef 5 月 21 日挑战对于某些值,例如 n=4589,我得到了错误的结果,任何帮助表示赞赏:)
/*对于给定的 N,找到从范围 [0,2N−1] 中选择整数 x 的方法数,使得 x⊕(x+1)=(x+2)⊕(x+3 ),其中 ⊕ 表示按位异或运算符。
由于有效x的个数可能很大,所以将其取模109+7输出。*/
#include <iostream>
using namespace std;
#define ll long long
const ll N = 1e5; //user can input n upto 1e5
unsigned ll arr[N];
unsigned ll p = 1e9 + 7; // we have to find answer modulo p
ll mod_pow(ll a,ll b)
{
if (b == 1)
{
return a;
}
ll c = 1;
if ( b % 2 == 0)
c= ( mod_pow ( a,b / 2) ) % p ;
else
{
c = ( mod_pow(a,(b - 1) / 2)) % p;
return ((a % p) * c * c) % p;
}
return (c * c)%p;
}
void pre()
{
for ( unsigned ll i = 0;i < N;i++)
{
arr[i] = ( ( ( ( mod_pow ( 2,i+1) -1 + p ) %p ) * 1/2 ) %p + 1 ) %p;
/ / precomputing for all even number in (2^n -1)
}
}
int main()
{
ios::sync_with_stdio(false);cin.tie(NULL);
pre();
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
cout << (arr[n-1])<<endl ;
}
return 0;
}
解决方法
实际上,解决方案只是 2 的幂:answer = 2^{n-1}
。
为了效率,这意味着最好先迭代计算所有解决方案:
powerof2[n] = (2 * powerof2[n-1]) % p
#include <iostream>
constexpr int N = 1e5; //user can input n up to 1e5
unsigned long long arr[N];
constexpr unsigned int p = 1e9 + 7; // we have to find answer modulo p
// pre-compute the powers of 2
void pre() {
arr[0] = 1;
for (int i = 1; i < N; i++) {
arr[i] = (2 * arr[i-1]) % p;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
pre();
int t;
std::cin >> t;
while (t--) {
int n;
std::cin >> n;
std::cout << arr[n-1] << std::endl ;
}
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。