洛谷训练新手村之“循环!循环!循环!”题解

P1008 三连击

题目链接:https://www.luogu.com.cn/problem/P1008
题目大意:找所有1:2:3格式的数。
解题思路:枚举一下第一个数,然后判断根据第一个数推导出来的第二、三个数是不是三位数即可,并且放好包含了1至9即可。
实现代码如下:

#include <bits/stdc++.h>
using namespace std;
bool tmp[10];
bool check(int a) {
    int b = a * 2, c = a * 3;
    if (b > 999 || c > 999) return false;
    int d = a * 1000000 + b * 1000 + c;
    memset(tmp, 0, sizeof(tmp));
    while (d) {
        tmp[d%10] = true;
        d /= 10;
    }
    for (int i = 1; i < 10; i ++) if (!tmp[i]) return false;
    return true;
}
int main() {
    for (int a = 123; a <= 333; a ++) {
        if (check(a)) {
            cout << a << " " << 2*a << " " << 3*a << endl;
        }
    }
    return 0;
}

P1035 级数求和

题目链接:https://www.luogu.com.cn/problem/P1035
题目大意:求题目所述表达式的值。
解题思路:循环到可大于K。
实现代码如下:

#include <bits/stdc++.h>
using namespace std;
double k, s;
int main() {
    cin >> k;
    for (int i = 1; ; i ++) {
        s += 1.0 / (double) i;
        if (s > k) {
            cout << i << endl;
            break;
        }
    }
    return 0;
}

P1423 小玉在游泳

题目链接:https://www.luogu.com.cn/problem/P1423
题目大意:
小玉开心的在游泳,可是她很快难过的发现,自己的力气不够,游泳好累哦。已知小玉第一步能游2米,可是随着越来越累,力气越来越小,她接下来的每一步都只能游出上一步距离的98%。现在小玉想知道,如果要游到距离x米的地方,她需要游多少步呢。请你编程解决这个问题。
解题思路:循环加上每步的距离,直到路程 \(\ge x\)
实现代码如下:

#include <bits/stdc++.h>
using namespace std;
double s, x, v = 2; // s表示路程,v表示速度
int main() {
    cin >> x;
    for (int i = 1; ; i ++) {
        s += v;
        v *= 0.98;
        if (s >= x) {
            cout << i << endl;
            break;
        }
    }
    return 0;
}

P1424 小鱼的航程(改进版)

题目链接:https://www.luogu.com.cn/problem/P1424
题目大意:问一只周末休息的小鱼从周x开始的n天一共游了多少距离。
解题思路:实现最简单的方法就是每天遍历一遍。
实现代码如下:

#include <bits/stdc++.h>
using namespace std;
int x, n, s;
int main() {
    cin >> x >> n;
    x --;
    while (n --) {
        if (x < 5) s += 250;
        x = (x + 1) % 7;
    }
    cout << s << endl;
    return 0;
}

P1980 计数问题

题目链接:https://www.luogu.com.cn/problem/P1980
题目大意:计算从1到n的所有整数中x出现的次数。
解题思路:枚举每个数,然后枚举每一位。
实现代码如下:

#include <bits/stdc++.h>
using namespace std;
int n, x, cnt;
void solve(int a) {
    while (a) {
        if (a%10 == x) cnt ++;
        a /= 10;
    }
}
int main() {
    cin >> n >> x;
    for (int i = 1; i <= n; i ++) solve(i);
    cout << cnt << endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/quanjun/p/11924507.html