《李白沽酒》:
李白无事街上走,提壶去打酒.
遇店加一倍,见花喝一斗.
五遇店和花,喝光壶中酒.
试问此壶中,原有多少酒?
原诗是三遇店和花,这里改成了五次,后面有提示:由于古代没有小数,所以都用整数。
假设,壶中酒数都是整数,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int time = 5;//李白经过多少个店就写多少吧。
Dictionary<int, List<int>> dic = new Dictionary<int, List<int>>();
dic[time + 1] = new List<int>();
dic[time + 1].Add(0);
for (int i = time; i >= 1; i--)
{
dic[i] = new List<int>();
foreach (int amount in dic[i + 1])
{
List<int> listsub = GetSource(amount);
foreach (var item in listsub)
{
if (!dic[i].Contains(item)) dic[i].Add(item);
}
}
}
Console.Write("第" + 1 + "次经过前:\t");
dic[1].Sort();
foreach (int amount in dic[1])
{
Console.Write(amount + ", ");
}
Console.Write("\n");
Console.Read();
}
//根据经过点后判断点前酒数量
public static List<int> GetSource(int amount)
{
List<int> list = new List<int>();
list.Add((int)(amount + 1));
if (amount > 0 && (amount % 2 == 0))
{
list.Add(amount / 2);
}
return list;
}
}
}
结果(单位:斗):
二、假设壶中酒数量可以为小数:
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int time = 5;//李白经过多少个店就写多少吧。
Dictionary<int, List<double>> dic = new Dictionary<int, List<double>>();
dic[time + 1] = new List<double>();
dic[time + 1].Add(0.0);
for (int i = time; i >= 1; i--)
{
dic[i] = new List<double>();
foreach (double amount in dic[i + 1])
{
List<double> listsub = GetSource(amount);
foreach (var item in listsub)
{
if (!dic[i].Contains(item)) dic[i].Add(item);
}
}
}
Console.Write("第" + 1 + "次经过前:\t");
dic[1].Sort();
foreach (double amount in dic[1])
{
Console.Write(amount + ", ");
}
Console.Write("\n");
Console.Read();
}
//根据经过点后判断点前酒数量
public static List<double> GetSource(double amount)
{
List<double> list = new List<double>();
list.Add(amount + 1);
if (amount > 0)
{
list.Add(amount / 2);
}
return list;
}
}
}
结果(单位:斗):