<OJ_Sicily>Greatest Common Divisors

40 篇文章 0 订阅

Description

A common divisor for two positive numbers is a number which both numbers are divisible by. It's easy to calculate the greatest common divisor between tow numbers. But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low<=d<=high. It is possible that there is no common divisor in the given range.

Input

The first line contains an integer T (1<=T<=10)- indicating the number of test cases.

For each case, there are four integers a, b, low, high (1<=a,b<=1000,1<=low<=high<=1000) in one line.

题目解释:求解两个数a和b在范围low和high之间的最大公约数。实质就是求a和b的公约数,然后符合该公约数在范围low和high之间是最大的

解题思路:使用一个for循环,从a和b中取较小的数,假如较小数是b,从b开始逐渐减一求得符合要求的值

#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
    // insert code here...
    int T, a, b, low, high;
    cin >> T;
    while (T > 0) {
        cin >> a >> b >> low >> high;
        int tmp = 0;
        if (a < b) {
            tmp = a;
            a = b;
            b = tmp;
        }
        bool has_answer = false;
        int result = 0;
        for (int i = b; i >= 1 ; i--) {   // 从小的数开始,逐个找到符合要求的值
            if ((b % i) == 0 && (a % i) == 0 && i >= low && i <= high) {
                has_answer = true;
                result = i;
                break;
            }
        }
        if (has_answer) cout << result<< endl;
        else cout << "No answer" << endl;
        T--;
    }
    return 0;
}


如果要在不使用 `#include <unordered_set>` 的情况下实现类似功能,我们可以使用数组或列表来模拟邻接表,并使用位运算来标记已访问的箱子。这里是一个基于数组的解决方案: ```cpp #include <iostream> #include <vector> using namespace std; const int MAX_N = 100; // 假设箱子不超过100个 // 用一个布尔数组表示箱子是否被访问过,初始化全为false bool visited[MAX_N + 1]; // 定义邻接矩阵,使用二维数组表示箱子之间的钥匙关系 vector<vector<int>> graph(MAX_N + 1, vector<int>(MAX_N + 1)); void findUnlockable(int n, vector<int>& graph, vector<int>& result) { // 初始化遍历标志 for (int i = 0; i <= n; ++i) { visited[i] = false; } // 从第一个箱子开始,进行深度优先搜索 dfs(1, graph, result); } void dfs(int node, vector<int>& graph, vector<int>& result) { // 标记当前箱子已访问 visited[node] = true; // 添加当前箱子到结果中 result.push_back(node); // 遍历邻居节点 for (int nei : graph[node]) { // 如果邻居未被访问,则递归继续搜索 if (!visited[nei]) { dfs(nei, graph, result); } } } int main() { int n, m; cin >> n >> m; // 读取钥匙隐藏关系并更新邻接矩阵 for (int i = 0; i < m; ++i) { int u, v; cin >> u >> v; graph[u][v] = 1; // 表示箱子u的钥匙在箱子v中,这里的1只是一个标记 } vector<int> unlockable; // 用于存储结果 findUnlockable(n, graph, unlockable); // 输出结果 for (int box : unlockable) { cout << box << " "; } cout << endl; return 0; } ``` 请注意,这种方法仅适用于箱子数量较小的情况,因为数组大小是固定的,不适合大规模的数据。如果输入规模未知或者可能会很大,建议还是使用 `unordered_set` 或其他哈希集合来优化查找效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值