2021-07-19 AcWing 3773. 兔子跳

输入样例:

4
2 4
1 3
3 12
3 4 5
1 5
5
2 10
15 4

输出样例:

2
3
1
2

思路:①当 ai = x, min = 1;

        ②当存在 ai > x(且不存在 ai = x), min = 2;

        ③当所有ai均小于x时,取max(ai/x的上取整),即找到此时最大的ai

一开始是这样写的,超时了

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

int main()
{
    int t;
    int m,n,x;
    cin >> t;
    while(t--)
    {
        bool ret=false;
        int res=0;
        cin >> n >> x;
        for (int i = 0; i < n; i ++ ){
            cin >> m;
            if(m==x){
                res=1;
                ret=true;
            }else if(m>x){
                res=2;
            }else{
                if(!res) res=x/m+1;
                else res=min(res,x/m+1);
            }
            
            if(ret) break;
        }
        cout << res <<endl;
    }
    return 0;
}

改进后

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

int main()
{
    int t;
    int m,n,x;
    cin >> t;
    while(t--)
    {
        bool ret=false;
        int res=0;
        cin >> n >> x;
        for (int i = 0; i < n; i ++ ){
            cin >> m;
            if(m==x){
                ret=true;
            }
            res=max(res,m);
        }
        if(ret){
            printf("1\n");
        }else if(res>x){
            printf("2\n");
        }else{
            printf("%d\n",(x+res-1)/res);//上取整
        }
    }
    return 0;
}

posted @ 2021-07-19 20:02  泥烟  阅读(26)  评论(0编辑  收藏  举报