2019-06-08 YTUOJ 算法/查找

--------------------------------
Author : ShawnDong
updateDate :2019.6.8
Blog : ShawnDong98.github.io
--------------------------------

3332: 二分查找: 小C同学有n个苹果,每个苹果的甜度都不相同,他现在想要吃一个甜度为a的苹果,可他又不想一个个去找,聪明的你能帮他在最少次数(相对次数最少)内找出甜度为a的苹果吗。

int binarySearch(int a[], int n, int target){
    int mid,count = 0,left = 1, flag = 0;
    while(left <= n){
        count++;
        mid = left+ (n-left)/2;
        if (a[mid] == target) {
            cout << count;
            flag = 1;
            break;
        }
        else if (a[mid] > target) n = mid-1;
        else left = mid+1;
    }
    if(flag==0){
        cout<<"I can't find it.";
    }
}

int main(){
    int n;
    cin >> n;
    int a[n+1];
    for(int i = 1;i <= n;i ++)
        cin >> a[i];
    int target;
    cin>>target;
    binarySearch(a, n, target);
    return 0;
}

3345: 求对角线之和:输入一个3*3的数组,求其一条对角线(右上到左下)的和。如下图粗体所示:

int main(){
    int a[3][3];
    int sum = 0;
    for(int i=0; i<3; i++){
        for(int j=0; j<3; j++){
            cin >> a[i][j];
            if(2 - i == j){
                sum += a[i][j];
            }
        }
    }
    cout << sum;
    return 0;
}

3346: 判断闰年:输入一个年份,判断是否是闰年,若是,判断其为普通闰年还是世纪闰年。
普通闰年:能被4整除但不能被100整除的年份为普通闰年。(如2004年就是闰年,1999年不是闰年);
世纪闰年:能被400整除的为世纪闰年。(如2000年是闰年,1900年不是闰年);
若是普通闰年,输出common leapyear;
若是世纪闰年,输出century leapyear;

若不是闰年,输出no leapyear;

int main(){
    int year;
    cin >> year;
    if(year % 4 == 0 && year % 100 != 0){
        cout << "common leapyear";
    }
    else if(year % 400 == 0){
        cout << "century leapyear";
    }
    else{
        cout << "no leapyear";
    }
    return 0;
}

你可能感兴趣的:(2019-06-08 YTUOJ 算法/查找)