NOI:8186 判断元素是否存在

题目链接:http://noi.openjudge.cn/ch0113/41/

41:判断元素是否存在

总时间限制: 1000ms 内存限制: 65536kB 
描述 
有一个集合M是这样生成的: (1) 已知 k 是集合 M 的元素; (2) 如果 y 是 M 的元素,那么, 2y+1 和 3y+1 都是 M 的元素; (3) 除了上述二种情况外,没有别的数能够成为 M 的一个元素。

问题:任意给定 k 和 x,请判断 x 是否是 M 的元素。这里的 k是无符号整数,x 不大于 100000, 如果是,则输出YES,否则,输出 NO

输入 
输入整数 k 和 x, 逗号间隔。 
输出 
如果是,则输出 YES,否则,输出NO 
样例输入 
0,22 
样例输出 

YES

方法1:递归

思路:可以使用递归,注意终止条件,即当元素大于x时,终止当前递归

     递归返回条件2*k+1和3*k+1任意一个成立即可

#include <stdio.h>
#include <iostream>
#include <queue>
using namespace std;
int k,x;
bool f(int y){
    if(y>x)return false;
    if(y==x)return true;
    if(f(2*y+1)||f(3*y+1))return true;
    return false;
}
int main(){
    cin>>k;
    cin.get();
    cin>>x;
    int a=k;
    bool b=f(a);
    if(b)cout<<"YES"<<endl;
    else cout<<"NO"<<endl;
}

方法2:排序

思路:类似于题目2729,按照一定的顺序计算集合

#include <stdio.h>
#include <iostream>
#include <set>
#include <iterator>
#include <queue>
using namespace std;
int a,n;
int all[1000005];
int main(){
    char t2;
    cin>>a>>t2>>n;
        int x,y,head1=1,head2=1,t=1;
        all[1]=a;
        while(true){
            x=all[head1]*2+1;
            y=all[head2]*3+1;
            if(all[t]==n){
                cout<<"YES"<<endl;
                return 0;
            }
            if(all[t]>n){
                cout<<"NO"<<endl;
                return 0;
            }
            if(x<y)
            {
                                t++;
                all[t]=x;

                head1++;
            }else if(x>y){
                                t++;
                all[t]=y;

                head2++;
            }else if(x==y){
                                t++;
                all[t]=x;

                head1++;
                head2++;
            }
        }
    
}

                
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值