题解:P14069 初遇

· · 题解

题目简述

题意

给定 a,b,n,可以按照以下方法变换:

在此过程中 a,b 始终不能等于 n,问是否可以一直加下去。

思路

很简单,如果 a,b 能一直进行下去,那么一定存在一种方法使得 a>n 或 b>n,直接暴力广搜即可。

不断地变换 a,b,枚举每一种可能,但是 a,b,n \le 10^9,所以得用 map,但是结果显然会超时,用 unordered_map 并套两层即可。

优化

但如果只是这么做的话很容易超时,思考:其实 a,b 的大小关系和结果无关,所以我们只要一直保持 a<b 并进行广搜即可。

特判

AC 代码

#include <bits/stdc++.h>
using namespace std;
#define in cin
#define out cout
#define int long long
#define ios ios::sync_with_stdio(false), in.tie(nullptr), out.tie(nullptr)
inline void solve() {
    int a, b, n;
    unordered_map <int, unordered_map <int, bool>> mp;
    in >> a >> b >> n;
    if (a + b == n) { //特判
        out << "No\n";
        return;
    }
    if (a == n || b == n) {
        out << "No\n";
        return;
    }
    if (a == 0 || b == 0) {
        out << "Yes\n";
        return;
    }
    queue <pair <int, int>> q;
    q.push({a, b}), mp[a][b] = true; //初始化
    while (!q.empty()) {
        auto [x, y] = q.front();
        q.pop();
        if (x == n || y == n) //不行
            continue;
        if (x > n || y > n) { //有解
            out << "Yes\n";
            return;
        }
        x += y; //变换
        int k = min(x, y), k2 = max(x, y);
        x = k, y = k2; //保持x<y
        if (!mp[x][y])
            mp[x][y] = true, q.push({x, y});
    }
    out << "No\n";
}
signed main() {
    ios;
    int t;
    in >> t;
    while (t--) //t组数据
        solve();
    return 0;
}