challenge いちばん長いしりとり

単語のリストを読み込んで、そのリストにある単語で「しりとり」をします。
一番長くしりとりを続けるためのプログラムを書いてください。
また、単語数に対して、計算量がどのように増えていくかも考えて下さい。

なお、単語リストの一例として
http://www.ais.riec.tohoku.ac.jp/lab/wordlist/index-j.htmlで公開されている
http://www.ais.riec.tohoku.ac.jp/lab/wordlist/fam55_40.txtがあります。

ただし、
・一度使った単語は使わないこと(リストに重複がある可能性は考えなくてよい)
・「ん」で終わる単語を使用するか、リスト内にしりとりを続けられる単語がなくなったときに、しりとりは終了する
・一番最初は、好きな単語から初めてもよい
・「一番長くしりとりを続ける」とは、しりとりが終了するまでに使用する単語数が最大になるよう、しりとりの単語を選ぶことをいう

Posted feedbacks - C#

とりあえずの愚直実装。 350語くらいなら一瞬ででるんですが、 その先はぜんぜん終わる気配がないです。

 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class Word
{
    public string Tango{get;set;}
    public bool Used{get;set;}

    public Word(string t)
    {
        Tango = t;
        Used = false;
    }

    public char First()
    {
        return Tango.First();
    }

    public char Last()
    {
        return Tango.Last();
    }
}

class Program
{
    static Dictionary<char, List<Word>> wordDic = new Dictionary<char, List<Word>>();
    static List<Word> wordList = new List<Word>();
    static int count = 0;
    static int maxcount = 0;

    static void Add(Word word)
    {
        List<Word> list;

        if (wordDic.ContainsKey(word.First()))
        {
            list = wordDic[word.First()];
        }
        else
        {
            list = new List<Word>();
            wordDic[word.First()] = list;
        }

        list.Add(word);
    }

    static void Main(string[] args)
    {
        using (StreamReader sr = new StreamReader("D:\\tango.txt"))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                Word w = new Word(line);
                Add(w);
                wordList.Add(w);
            }
        }

        foreach (Word word in wordList)
        {
            Shiritori(word);
        }

        Console.WriteLine("Finish");
        Console.Read();
    }

    private static void Shiritori(Word word)
    {
        word.Used = true;
        ++count;

        if (wordDic.ContainsKey(word.Last()))
        {
            foreach (Word t2 in wordDic[word.Last()])
            {
                if (t2.Used == false)
                {
                    Shiritori(t2);
                }
            }
        }

        SetCount(count);
        --count;
        word.Used = false;
    }

    private static void SetCount(int count)
    {
        if (maxcount < count)
        {
            maxcount = count;
            Console.WriteLine(maxcount);
        }
    }
}

Index

Feed

Other

Link

Pathtraq

loading...