Comment detail

情報オリンピック2007年度国内本選問題1 (Nested Flatten)

とりあえず、Javaで解いて見ました。 あまり無駄はないと思いますが、autoboxingなところがちょっといまいちですね・・・。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Sample158 {
    private final List<Integer> countList_;
    private int last_;

    public Sample158(int n) {
        countList_ = new ArrayList<Integer>(n);
    }

    public void add(int index, int c) {
        if (index == 1) {
            countList_.add(1);
        } else if (last_ == c) {
            lastAdd(countList_, 1);
        } else {
            if ((index & 1) != 0) {
                countList_.add(1);
            } else {
                int lastCount = countList_.remove(countList_.size() - 1);
                if (countList_.isEmpty()) {
                    countList_.add(lastCount + 1);
                } else {
                    lastAdd(countList_, lastCount + 1);
                }
            }
        }
        last_ = c;
    }
    private void lastAdd(List<Integer> list, int add) {
        int lastIndex = list.size() - 1;
        int value = list.get(lastIndex);
        list.set(lastIndex, value + add);
    }

    public int calc() {
        int result = 0;
        for (int index = countList_.size() - last_ - 1; index >= 0; index -= 2) {
            result += countList_.get(index);
        }
        return result;
    }


    public static void main(String[] args) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        try {
            int n = Integer.parseInt(reader.readLine());
            Sample158 sample = new Sample158(n);
            for (int index = 0; index < n; index++) {
                int c = Integer.parseInt(reader.readLine());
                sample.add(index + 1, c);
            }
            int result = sample.calc();
            System.out.println(result);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Index

Feed

Other

Link

Pathtraq

loading...