[算法设计与分析]4.4.2相对或近似贪婪问题(币种统计问题+取数游戏)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Pecony/article/details/80197108
#include<cstdio>
#include<iostream>
#include<cstring>

using namespace std;

void CoinStatistics();

void SelectNum();

int main ()
{
    CoinStatistics();
    SelectNum();
}

void CoinStatistics()//本函数的作用是统计发给所有员工工资的各面额张数最少分别需要多少
{
    int i, j, A;
    int n = 3;//n代表人数
    int GZ[n] = {200, 150, 230};//假定有三个人 初始化每个人应分配的钱数
    int B[8] = {0, 100, 50, 20, 10, 5, 2, 1};//B中存储钱币的种类
    int S[8] = {0};//代表每种面额的钱的张数 必须初始化为0

    for(i = 0; i < n; i++)//代表每人工资的数组从0开始有效
    {
        for(j = 1; j <= 7; j++)//代表钱币种类的数组从1开始有效
        {
            A = GZ[i] / B[j];//因为要求钱张数最少 而且钱的面额数组为降序 A代表当前面额的钱币需要的张数
            S[j] = S[j] + A;
            GZ[i] = GZ[i] - A * B[j];//每次从总额中减去已经分配的张数金额之和
        }
    }
    for(int k = 1; k <= 7; k++)
        {
            cout << B[k] << "------" << S[k] << endl;
        }
        cout << endl;
}

void SelectNum()
{
    int i, s1, s2;
    int n = 10;//假定有n个数
    s1 = 0;//s1和s2中分别存储奇数项和偶数项的和
    s2 = 0;
    int data[n + 1] = {0, 1, 2, 3, 10, 5, 6, 7, 8, 9, 4};//一定要保证数列的有效长度是偶数 即n为偶数 否则奇偶项个数不一样

    for(i = 1; i <= n; i++)
    {
        if(i % 2)//奇数项
            s1 += data[i];
        else//偶数项
            s2 += data[i];
    }
    if(s1 > s2)//证明奇数项之和大于偶数项之和 因此应该从左边开始取
        cout << "first take left" << endl;
    else
        cout << "first take right" << endl;
}

猜你喜欢

转载自blog.csdn.net/Pecony/article/details/80197108
今日推荐