博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HackerRank "Xor and Sum"
阅读量:5491 次
发布时间:2019-06-16

本文共 1829 字,大约阅读时间需要 6 分钟。

Actually I think it should belong to category of 'Bits Manipulation'.. but still, a really good one.

My first reaction was, how to derive from a ^ (b << i) from a ^ (b << (i - 1)), but after some thoughts, I figured out that that should not be the way to go: there's no easy way to do that induction. 

This one resembles with another Bit one: we are to calculate sum, so we consider bit by bit: at bit[i], it contributes bit[i] << i to the final sum..

Lesson learnt: 1) power2 can be moduled too; 2) VISUALIZE the problem space\process in your mind - it is crucial.

#include 
#include
#include
#include
#include
#include
using namespace std;#define MOD 1000000007unsigned sum(vector
&ones, int l, int r){ l = std::max(0, l); r = std::min(int(ones.size() - 1), r); if (l > r) return 0; return ones[r] - (l == 0 ? 0 : ones[l - 1]);}int main() { const unsigned N = 314159; const unsigned NMAX = 1e6; string a, b; std::cin >> a >> b; std::reverse(a.begin(), a.end()); std::reverse(b.begin(), b.end()); // Power2 % MOD vector
pw2(NMAX); pw2[0] = 1; for (unsigned i = 1; i < NMAX; i++) pw2[i] = (pw2[i - 1] * 2LL) % MOD; // Count accumulative count of ones size_t lena = a.length(); size_t lenb = b.length(); vector
ones(lenb, 0); for (int i = 0; i < lenb; i++) { ones[i] = b[i] - '0'; if (i > 0) ones[i] += ones[i - 1]; } // Count accumulative count of zeros unsigned ans = 0; for (int i = 0; i < NMAX; i++) { int bita = (i >= lena) ? 0 : a[i] - '0'; int cnt_ones = sum(ones, i - N, i); if (bita) { ans = (unsigned)((ans + (N + 1 - cnt_ones) * 1LL * pw2[i]) % MOD); } else { ans = (unsigned)((ans + cnt_ones * 1LL * pw2[i]) % MOD); } } cout << ans << endl; return 0;}

转载于:https://www.cnblogs.com/tonix/p/4654337.html

你可能感兴趣的文章
传值引用和调用引用的区别
查看>>
Hive简介
查看>>
hyper-v 无线网连接
查看>>
Python3.7.1学习(六)RabbitMQ在Windows环境下的安装
查看>>
Windows下memcached的安装配置
查看>>
ubuntu: firefox+flashplay
查看>>
常见的海量数据处理方法
查看>>
C语言博客作业03--函数
查看>>
web.xml 中CharacterEncodingFilter类的学习
查看>>
贪吃蛇逻辑代码
查看>>
实现c协程
查看>>
ASP.NET视频教程 手把手教你做企业论坛网站 视频教程
查看>>
[LeetCode] Meeting Rooms II
查看>>
从Swift学习iOS开发的路线指引
查看>>
3.1链表----链表(Linked List)入门
查看>>
Scribes:小型文本编辑器,支持远程编辑
查看>>
ssh 安装笔记
查看>>
游戏音效下载网站大全
查看>>
实验五
查看>>
程序包+创建包规范+创建包体+删除程序包
查看>>