兔子藏洞

本文介绍了一种通过特定搜索模式来确定目标位置的算法。该算法适用于20个圆形排列的洞中寻找隐藏目标的问题,详细说明了输入输出格式及核心实现逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

一只兔子藏身于20个圆形排列的洞中(洞从1开始编号),一只狼从x号洞开始找,下次隔一个洞找(及在x+2号洞找),在下次个两个洞找(及在x+5号洞找),它找了n次仍然没有找到。问兔子可能在那些洞中。

输入描述:

输入有多组数据,每组数据一行两个整数分别为x和n(x <= 20,n <= 100000)

输出描述:

每组数据一行按从小到大的顺序输出兔子可能在的洞,数字之间用空格隔开。若每个洞都不肯能藏着兔子,输出-1。


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            // String[] split = sc.nextLine().split(" ");
            // int x = Integer.parseInt(split[0]);
            // int n = Integer.parseInt(split[1]);
            int x = Integer.parseInt(sc.next());
            int n = Integer.parseInt(sc.next());
            System.out.println(fun(x, n));
        }
        sc.close();

    }

    private static String fun(int x, int n) {
        int[] a = new int[20];
        for (int i = 0; i < 20; i++) {
            a[i] = i + 1;
        }

        for (int i = 1; i <= n; i++) {
            int findNum = (x + (i + 1) * i / 2 - 1) > 20 ? (x + (i + 1) * i / 2 - 1) % 20 : (x + (i + 1) * i / 2 - 1);
            if (findNum != 0 && a[findNum - 1] != -1) {
                a[findNum - 1] = -1;
            } else if (findNum == 0) {
                a[19] = -1;
            }
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 20; i++) {
            if (a[i] != -1) {
                sb.append(a[i]).append(" ");
            }
        }
        if (sb.length() == 0)
            return "-1";
        return sb.toString();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值