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

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 visited = new HashSet();

    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 wait = new LinkedList();
        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找牛不是一个套路吗?!

你可能感兴趣的:(ACM,搜索)