hdu 5491 The Next 2015合肥网络赛 贪心 位运算
2015-09-28 13:13
405 查看
题目
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5491题目来源:2015合肥网络赛签到题。这套题质量比较高
简要题意:xx二进制含有11的个数为cnt(x)cnt(x),S1⩽cnt(x)⩽S2S_1 \leqslant cnt(x) \leqslant S_2则xx是WTH数
\qquad \quad \ \ \ \ 求大于DD的第一个WTH数。
数据范围:T⩽300000;0⩽D<231;DT\leqslant 300000;\quad 0\leqslant D<2^{31};\quad D是WYH数
题解
虽然是签到题,但是这题当时卡了我挺久的,然后最后转手给学长了。贪心的题目需要制定最好的策略,很容易思路混乱而导致错误。
基本的策略是从低位到高位找为00的位,这些位填上了11之后这个数一定是比DD大的。
然后该位之后的所有位就都可以任意设置了。
之后再去判断是否能够设置为目标的数就行了。
实现
要知道一个数有多少位其实是有Θ(loglen)\Theta(\log len)的算法的,lenlen是数的二进制占位。这是一个分治的小技巧,可以去看下Matrix67的位运算讲稿学下。
然后g++内部也有用硬件实现的函数
__builtin_popcount。
做的时候就是扫一遍,对于11把它置为00,对于00去判断当前置为11用之后的位内否达到目标。
代码
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <cstring> #include <stack> #include <queue> #include <string> #include <vector> #include <set> #include <map> #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define sz(x) ((int)(x).size()) #define fi first #define se second using namespace std; typedef long long LL; typedef vector<int> VI; typedef pair<int,int> PII; LL powmod(LL a,LL b, LL MOD) {LL res=1;a%=MOD;for(;b;b>>=1){if(b&1)res=res*a%MOD;a=a*a%MOD;}return res;} // head inline int bitCount(LL x) { x = (x & 0x5555555555555555LL) + ((x >> 1) & 0x5555555555555555LL); x = (x & 0x3333333333333333LL) + ((x >> 2) & 0x3333333333333333LL); x = (x & 0x0F0F0F0F0F0F0F0FLL) + ((x >> 4) & 0x0F0F0F0F0F0F0F0FLL); x = (x & 0x00FF00FF00FF00FFLL) + ((x >> 8) & 0x00FF00FF00FF00FFLL); x = (x & 0x0000FFFF0000FFFFLL) + ((x >> 16) & 0x0000FFFF0000FFFFLL); x = (x & 0x00000000FFFFFFFFLL) + ((x >> 32) & 0x00000000FFFFFFFFLL); return x; } LL solve(LL d, int l, int r) { for (int i = 0; i < 64; i++) { int cnt = bitCount(d); if ((d & (1LL<<i)) == 0 && cnt+1 <= r && cnt+i+1 >= l) { return d | (1LL<<i) | ((1LL<<max(l-cnt-1, 0))-1); } d &= -1LL^(1LL<<i); } } int main() { int t, l, r, cas = 1; LL d; scanf("%d", &t); while (t--) { scanf("%I64d%d%d", &d, &l, &r); printf("Case #%d: %I64d\n", cas++, solve(d, l, r)); } return 0; }
相关文章推荐
- iOS:网络编程的第三方框架:AFNetworking、SDWebImage
- 那么温暖http合约,入门。
- HTTP求
- .net mvc 一个Action的 HttpGet 和 HttpPost
- 简述tcp协议对http性能的影响及优化
- apache旧版本下载地址:http://archive.apache.org/dist/httpd/
- HTTP POST GET 请求区别详解
- 简述tcp协议对http性能的影响及优化
- HDU 5476 Explore Track of Point (2015年上海赛区网络赛I题)
- okhttp maven下载地址
- 用 C# 实现 HTTP 协议多线程下载文件
- OkHttp使用教程
- nginx 配置 ssl 模块支持 https
- 使用java实现http多线程下载
- Android HTTP Content-type( Mime-Type)对照表
- Halcon学习 多层神经网络
- vim的配置文件。转自:http://www.cnblogs.com/ma6174/
- Cookie对象HttpOnly和secure属性
- Swift - 同步请求获取网络数据
- tomcat https 配置