HDU 5297 Y sequence(容斥+迭代)
2016-01-05 16:04
155 查看
Description
给定整数n和整数r,在1、2、3、4、5…….的序列中删掉可以开2次方的数,3次方的数,4次方的数,…….r次方的数,剩下的数称为Y序列,求Y序列中第n个数是多少
Input
第一行为一个整数T表示用例组数,每组用例为两个整数n和r
(n<=2*10^18,2<=r<=62,T<=30000)
Output
对于每组用例,输出Y序列中第n个数
Sample Input
2
10 2
10 3
Sample Output
13
14
Solution
先考虑如何求出m之内属于Y序列数字的数量,m以内可以开2次方的数有pow(m,1/2)个,开3次方的数有pow(m,1/3)个…所以这个数量可以容斥来求,先预处理1~63中所有的素数,然后对这些素数容斥,统计r中每个数的素因子个数,偶减奇加(在处理素数时加一个负号就避免了判断素因子数量的奇偶),现在我们已经知道了如何求m内有多少属于Y序列的数字,那如何得知Y序列的第n个数呢?这个可以迭代解决,假设n以内有num个Y序列的数,如果num< n,那么去统计n+n-num内属于Y序列的数字,一直迭代到num=n为止,这种迭代显然是对的是因为多加的n-num中最多只有n-num个数字属于Y序列,当多加的数等于缺的数那么就得到答案了,而且永远不可能超过答案
Code
给定整数n和整数r,在1、2、3、4、5…….的序列中删掉可以开2次方的数,3次方的数,4次方的数,…….r次方的数,剩下的数称为Y序列,求Y序列中第n个数是多少
Input
第一行为一个整数T表示用例组数,每组用例为两个整数n和r
(n<=2*10^18,2<=r<=62,T<=30000)
Output
对于每组用例,输出Y序列中第n个数
Sample Input
2
10 2
10 3
Sample Output
13
14
Solution
先考虑如何求出m之内属于Y序列数字的数量,m以内可以开2次方的数有pow(m,1/2)个,开3次方的数有pow(m,1/3)个…所以这个数量可以容斥来求,先预处理1~63中所有的素数,然后对这些素数容斥,统计r中每个数的素因子个数,偶减奇加(在处理素数时加一个负号就避免了判断素因子数量的奇偶),现在我们已经知道了如何求m内有多少属于Y序列的数字,那如何得知Y序列的第n个数呢?这个可以迭代解决,假设n以内有num个Y序列的数,如果num< n,那么去统计n+n-num内属于Y序列的数字,一直迭代到num=n为止,这种迭代显然是对的是因为多加的n-num中最多只有n-num个数字属于Y序列,当多加的数等于缺的数那么就得到答案了,而且永远不可能超过答案
Code
#include<cstdio> #include<iostream> #include<algorithm> #include<cstring> #include<cmath> #include<vector> using namespace std; #define maxn 63 typedef long long ll; int prime[maxn],is_prime[maxn],res; vector<int>vec; void get_prime(int n) { memset(is_prime,0,sizeof(is_prime)); res=0; for(int i=2;i<n;i++) if(!is_prime[i]) { prime[res++]=-1*i; for(int j=i;j<n;j+=i) is_prime[j]=1; } } void get_factor(int r) { vec.clear(); for(int i=0;i<res&&-1*prime[i]<=r;i++) { int num=vec.size(); for(int j=0;j<num;j++) if(abs(vec[j]*prime[i])<=maxn) vec.push_back(vec[j]*prime[i]); vec.push_back(prime[i]); } } ll get_num(ll n) { ll ans=0; for(int i=0;i<vec.size();i++) { ll temp=(int)pow(n+0.5,abs(1.0/vec[i]))-1; ans+=(vec[i]<0?1:-1)*temp; } return n-ans-1; } int main() { get_prime(maxn); int T,r; ll n; scanf("%d",&T); while(T--) { scanf("%lld%d",&n,&r); get_factor(r); ll ans=n,num=get_num(n); while(num<n) { ans+=n-num; num=get_num(ans); } printf("%I64d\n",ans); } return 0; }
相关文章推荐
- PHP中break及continue两个流程控制指令区别分析
- iOS 8以上uitableviewcell的分割线左边对齐
- UILabel自适应高度和自动换行
- android View Hierarchry for UI
- ArcGIS 中UniqueValueRenderer和SimpleRenderer的异同点
- 源码推荐(01.05B):控件悬停,UICollectionView滚动加载页面
- QUESTION 169 A database has three online redo log groups with one member each. A redo log member wit
- easyui tree onloadsuccess事件的心得
- easyui tree onloadSuccess 事件心得
- Power Builder的学习
- IOS学习之UITableViewCell动态计算高度(IOS8)
- 获取 request 中 json 数据
- requestLayout, invalidate和postInvalidate的异同
- 使用cordova/phonegap 开发应用前请阅读,环境搭建,UI选择,低端机性能问题解决
- LeeCode - Unique Binary Search Trees
- iOS 密码输入框(UITextField)
- Word Frequency
- poj 2034 Anti-prime Sequences(dfs)
- easy ui window 相关属性
- 解决ORA-00824: cannot set sga_target due to existing