uva 11636 Hello World!(宽....宽搜.....)

5 篇文章 0 订阅

When you first made the computer to print the sentence “Hello World!”, you felt so happy, not
knowing how complex and interesting the world of programming and algorithm will turn out to be.
Then you did not know anything about loops, so to print 7 lines of “Hello World!”, you just had to
copy and paste some lines. If you were intelligent enough, you could make a code that prints “Hello
World!” 7 times, using just 3 paste commands. Note that we are not interested about the number
of copy commands required. A simple program that prints “Hello World!” is shown in Figure 1. By
copying the single print statement and pasting it we get a program that prints two “Hello World!”
lines. Then copying these two print statements and pasting them, we get a program that prints four
“Hello World!” lines. Then copying three of these four statements and pasting them we can get a
program that prints seven “Hello World!” lines (Figure 4). So three pastes commands are needed in
total and Of course you are not allowed to delete any line after pasting. Given the number of “Hello
World!” lines you need to print, you will have to find out the minimum number of pastes required to
make that program from the origin program shown in Figure 1.

卧槽同志们这题真的不是宽搜吗?!

我一眼看上去就觉得这是宽搜模板啊,然后就宽搜了,然后就ac了。结果被队友说思路清奇。好的我知道你们都是O(1)过的。网上的也都是贪心或者找规律………..
我以为全世界写这题都会用宽搜,结果只有我是奇葩吗orz

ac代码:

public class Main {
    static int[] step = new int[10005];
    static Set<Integer> visited = new HashSet<Integer>();

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int n = reader.nextInt();
        int cases = 1;
        slove(10001);
        while (n > 0) {
            System.out.print("Case " + (cases++) + ": ");
            System.out.println(step[n]);
            n = reader.nextInt();
        }
    }

    public static void slove(int n) {
        Queue<Integer> wait = new LinkedList<Integer>();
        wait.add(1);
        visited.add(1);
        int cur = 0;
        int next = 0;
        while (!wait.isEmpty()) {
            cur = wait.poll();
            for (int i = 1; i <= cur; i++) {
                next = cur + i;
                if (next >= 0 && next <= n) {//其实可以不用判范围....
                    if (visited.add(next)) {
                        step[next] = step[cur] + 1;
                        wait.add(next);
                    }
                    if (next == n) {
                        return;
                    }
                }
            }
        }
    }
}

这题真的跟farmer john找牛不是一个套路吗?!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值