最近在园子里的一位大哥的博客里看见了一个类似acm的网址,心里面就有些痒痒了,但是太菜了,这不,很快就遇到问题老,想了很久,实在是搞它不定啊,只有拖出来问问大家了,题目来源:http://acm.timus.ru/problem.aspx?space=1&num=1002
我目前的解决办法如下:
Solution
using System;
using System.Collections.Generic;
class Program
{
//private static string[] dic = new string[] { "oqz", "ij", "abc", "def", "gh", "kl", "mn", "prs", "tuv", "wxy" };
private static Dictionary<char, string> dic = new Dictionary<char, string>();
static Program()
{
dic.Add('0', "oqz");
dic.Add('1', "ij");
dic.Add('2', "abc");
dic.Add('3', "def");
dic.Add('4', "gh");
dic.Add('5', "kl");
dic.Add('6', "mn");
dic.Add('7', "prs");
dic.Add('8', "tuv");
dic.Add('9', "wxy");
}
private static bool TestWord(string numbers, string word)
{
bool result = true;
for (int i = 0; i < word.Length; i++)
{
if (dic[numbers[i]].IndexOf(word[i]) == -1)
{
result = false;
break;
}
}
return result;
}
static void Run()
{
string input = string.Empty;
string numbers = string.Empty;
int wordCount = 0;
while (true)
{
input = Console.ReadLine();
if (input.Trim() == "-1")
{
break;
}
numbers = input;
wordCount = int.Parse(Console.ReadLine());
List<string> words = new List<string>();
for (int i = 0; i < wordCount; i++)
{
words.Add(Console.ReadLine().Trim());
}
Pair p = new Pair(0, string.Empty);
p = Check(words, numbers, p);
if (p.Count == -1)
{
Console.WriteLine("No solution.");
}
else
{
Console.WriteLine(p.Result);
}
}
}
static Pair Check(List<string> words, string numbers, Pair pa)
{
Pair p = null;
bool flag = false;
int count = int.MaxValue;//记录符合条件的解决方案包含的单词数
foreach (string word in words)
{
if (word.Length == numbers.Length)
{
if (TestWord(numbers, word))
{
if (pa.Result.Length == 0)
{
return new Pair(pa.Count + 1, word);
}
else
{
return new Pair(pa.Count + 1, pa.Result + " " + word);
}
}
}
else if (word.Length < numbers.Length)
{
if (TestWord(numbers, word))
{
flag = true;
Pair temp = null;
if (pa.Result.Length == 0)
{
temp = Check(words, numbers.Substring(word.Length), new Pair(pa.Count + 1, word));
}
else
{
temp = Check(words, numbers.Substring(word.Length), new Pair(pa.Count + 1, pa.Result + " " + word));
}
if (temp.Count < count)
{
count = temp.Count;
p = new Pair(temp.Count, temp.Result);
}
}
}
}
if (!flag)
{
return new Pair(-1, string.Empty);
}
return p;
}
static void Main(string[] args)
{
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
Run();
}
class Pair
{
public Pair(int c, string r)
{
Count = c;
Result = r;
}
public int Count;
public string Result;
}
}
神啊,救救我吧...