c++ - Xor Equality(codechef may 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;
}
推荐阅读
- python - 媒体文件中的 React 和 Django 路由问题
- react-native - 在 React Native 中定位 View 的子节点
- c# - .Net Core 控制台日志记录未出现
- html - 怎么把图片放在文字旁边
- react-native - 从 props 数据创建 FlatList Grid
- email - 通过命令行将 SMTP 电子邮件保存到 IMAP Sent 文件夹。如何?
- jquery - 如何从选择多个中获取检查值
- java - 当我在代码编辑器中移动光标时,Eclipse IDE 中的“帮助”选项卡会发生变化
- regex - Git 冲突标记语法/规则是什么?
- android - Android AlertDialog 在多次显示和关闭时泄漏内存?