贪心算法-找零钱(C#实现)

找零钱这个问题很清楚,无非就是始终拿可以取的最大面值来找,最后就使得张数最小了,这个实现是在假设各种面值足够多的情况下。

首先拖出一个界面来,最下面是一个listbox控件

贪心算法-找零钱(C#实现)

对应的代码:问题比较简单,有注释

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

private void buttonOk_Click(object sender, EventArgs e)
        {
            if (listMoney.Items.Count != 0)   //第二次计算就清空,便于重复计算
                listMoney.Items.Clear();

var money = Exchange(Convert.ToDecimal(txtMoney.Text));

foreach (var single in money)
            {
                if (single.Value != 0)
                {
                    string s = string.Format("{0}元---->{1}张 ", single.Key, single.Value);
                    listMoney.Items.Add(s);
                }
            }

}
        Dictionary<decimal, int> GetInit()  //初始化字典
        {
            Dictionary<decimal, int> money = new Dictionary<decimal, int>();

//key表示钱,value表示钱的张数
            money.Add(100.00M, 0);
            money.Add(50.00M, 0);
            money.Add(20.00M, 0);
            money.Add(10.00M, 0);
            money.Add(5.00M, 0);
            money.Add(2.00M, 0);
            money.Add(1.00M, 0);
            money.Add(0.50M, 0);
            money.Add(0.20M, 0);
            money.Add(0.10M, 0);

return money;
        }

Dictionary<decimal, int> Exchange(decimal num)
        {
            var money = GetInit();

int i = 0;

while (true)
            {
                if (num < 0.1M)
                {
                    if (num > 0.05M)
                    {
                        money[0.10M]++; //大于0.05的时候给顾客0.1.
                        return money;
                    }
                    else
                        return money;  //否则就算了
                }

var max = money.Keys.ElementAt(i);  //取得面值

if (num >= max)
                {
                    num = num - max;
                    money[max] ++;   //money的张数自增
                }
                else
                    i++;  //就去取下一张面值
            }
        }
    }
}

上一篇:Spring众多jar包的特点,及Spring jar包官网下载方法


下一篇:bzoj2152 树分治