• 贪心算法解决钱币找零问题


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Coin
    {
        class Program
        {
            static void Main(string[] args)
            {
                int[] value = new int[] { 1, 2, 5, 10, 20, 50, 100 };
                int[] count = new int[] { 3, 0, 2, 1, 0, 3, 5 };
                int[] result = new int[count.Length+1];//将每个面额的货币使用数量记录下来,最后一个记录找零的情况
                CoinMoneny(600,value,count,result);//600块进行找零
                foreach (var item in result)//将找零的情况进行输出
                {
                    Console.WriteLine(item);
                }
                Console.ReadKey();
            }
            /// <summary>
            /// 对货币进行找零
            /// </summary>
            /// <param name="money"></param>
            /// <param name="value"></param>
            /// <param name="count"></param>
            /// <param name="result"></param>
            public static void CoinMoneny(int money,int[] value,int[] count,int[] result)
            {
                if (money <= 0)//先判断是否有找零的必要
                {
                    return;
    
                }
                int temp = value.Length - 1;//先从最大面额进行找零
                while(true)
                {
                    if(money>value[temp]*count[temp])//最大面额总数小于找零数
                    {
                        result[temp] = count[temp];//将最大面额所有的数量全部记录到数组中
                        money -= value[temp] * count[temp];//将最大面额使用完后的找零钱数
                    }
                    else//最大面额总数大于找零数
                    {
                        result[temp] = money / value[temp];//按照实际情况把找零的数量记录
                        money -= result[temp] * value[temp];//还剩下的找零数 
                    }
                    temp = temp - 1;//检测下一个面额的钱币
                    if(temp<0||money<=0)//终止查找
                    {
                        break;
                    }
                }
            }
           
        }
    }

  • 相关阅读:
    Centos5.8 安装 ImageMagick 6.8.9-3
    Centos5.8 安装 Redmine
    Apache配置中的ProxyPass 和 ProxyPassReverse
    Centos5.8 安装SVN并配置HTTP访问
    Centos5.8 安装 MySQL5.6.19
    Centos5.8 安装 PHP5.5 和 memcached
    CentOS RHEL 安装 Tomcat 7
    Centos5.8 iptables管理
    在SecureCRT中使用rz和sz传输文件
    在Mac mini上安装 ESXi 5.5
  • 原文地址:https://www.cnblogs.com/zhangyang4674/p/11319931.html
Copyright © 2020-2023  润新知