【问题标题】:Aibohphobia SPOJAibohphobia SPOJ
【发布时间】:2016-03-10 22:48:53
【问题描述】:

我正在尝试solve this exercise.

我有一个解决方案,如下所示,但我收到Time Limit Exceeded 错误。我想了解为什么这段代码效率低下,因为我正在做记忆。

namespace Aibohphobia
{
    class Test
    {
        static Dictionary<string, int> memo = new Dictionary<string, int>();
        static int Main(string[] args)
        {
            string num = Console.ReadLine();
            int N = int.Parse(num);
            string input = string.Empty;
            for (int i = 0; i < N; i++)
            {
                memo = new Dictionary<string, int>();
                input = Console.ReadLine();
                int count = new Test().insert(input, 0, input.Length - 1);
                Console.WriteLine(count);
            }
            return 0;
        }

        int insert(string input, int start, int end)
        {
            int count = 0;
            var key = start + "_" + end;

            if (start >= end)
                return 0;            
            if (memo.ContainsKey(key))
                return memo[key];
            if (input[start] == input[end])
            {
                count += insert(input, start + 1, end - 1);
            }
            else
            {
                int countLeft = 1 + insert(input, start + 1, end);
                int countRight = 1 + insert(input, start, end - 1);
                count += Math.Min(countLeft, countRight);
            }

            memo.Add(key, count);
            return count;
        }    
  }
}

【问题讨论】:

    标签: c# dynamic-programming memoization


    【解决方案1】:

    您正在将您的结果记忆Dictionary&lt;string, int&gt; 中,这本质上是一个哈希表。这意味着每次要检索给定键的值时,都必须计算该键的哈希函数。

    在这种情况下,由于您的密钥类型是string,因此对哈希函数的评估肯定会减慢您的执行速度。我建议你memoize你在int[][] matrix中的DP值,这样你就可以更快地检索到你想要的值。

    为了实现这一点,您将弄清楚如何将您的strings 映射到ints。您可以在此处找到有关如何执行此操作的简短教程:String Hashing for competitive programming,作者在这里解释了简单的 字符串散列 技术。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多