1. 程式人生 > >NOI:8186 判斷元素是否存在

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++;
            }
        }
    
}