题目链接: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++;
}
}
}