2016-05-06 131 views
-1

所以,我创建了一个硬币更改算法,采用值N和任何数量的面额,如果它没有1,我必须自动包括1。我已经这样做了,但现在有一个缺陷,我有2个矩阵,我需要使用其中的1个。是否有可能重写S [i]矩阵,并且仍然增加数组的大小......另外,我怎样才能找到最大面额和第二高和sooo直到最小?我应该把它从高到低排列,以便让它变得更容易,或者有更简单的方法来一个接一个地寻找它们吗?贪婪算法硬币更换C++

int main() 
{ 
    int N,coin; 
    bool hasOne; 
    cout << "Enter the value N to produce: " << endl; 
    cin >> N; 
    cout << "Enter number of different coins: " << endl; 
    cin >> coin; 

    int *S = new int[coin]; 

    cout << "Enter the denominations to use with a space after it" << endl; 
    cout << "(1 will be added if necessary): " << endl; 
    for(int i = 0; i < coin; i++) 
    { 
     cin >> S[i]; 
     if(S[i] == 1) 
     { 
      hasOne = true; 
     } 
     cout << S[i] << " "; 
    } 
    cout << endl; 
    if(!hasOne) 
    { 
     int *newS = new int[coin]; 
     for(int i = 0; i < coin; i++) 
     { 
      newS[i] = S[i]; 
      newS[coin-1] = 1; 
      cout << newS[i] << " "; 
     } 
     cout << endl; 
     cout << "1 has been included" << endl; 
    } 

    //system("PAUSE"); 
    return 0; 
} 
+0

我会建议只是其中分类到你所需要的顺序。我不确定为什么你加1,如果“必要” - 对于没有硬币值为1的货币呢?例如,从1950年到2000年,[里拉硬币](https://en.wikipedia.org/wiki/Coins_of_the_Italian_lira)正在使用,即使有的话,仍然有1个里拉硬币仍在流通。 –

+0

是的,但我们不想要这里的情况33我们不能得到它,因为没有1,所以这是必要的 – Darkflame

+0

如果用户输入无意义的输入,你应该告诉他们。你无法知道错误是否输入了33个金币或者不包括1个硬币。无论是否需要,您都要加1。 –

回答

1

你可以用std :: vector实现它,那么你只需要使用push_back

std::sort可用于按降序排列面值,然后只是检查最后一个是否为1,如果缺失则添加它。 (这段代码中缺少很多错误检查,例如,您应该检查没有面值> = 0,因为您使用的是有符号整数)。

#include <iostream> // for std::cout/std::cin 
#include <vector>  // for std::vector 
#include <algorithm> // for std::sort 

int main() 
{ 
    std::cout << "Enter the value N to produce:\n"; 
    int N; 
    std::cin >> N; 

    std::cout << "Enter the number of different denominations:\n"; 
    size_t denomCount; 
    std::cin >> denomCount; 

    std::vector<int> denominations(denomCount); 
    for (size_t i = 0; i < denomCount; ++i) { 
     std::cout << "Enter denomination #" << (i + 1) << ":\n"; 
     std::cin >> denominations[i]; 
    } 

    // sort into descending order. 
    std::sort(denominations.begin(), denominations.end(), 
     [](int lhs, int rhs) { return lhs > rhs; }); 

    // if the lowest denom isn't 1... add 1. 
    if (denominations.back() != 1) 
     denominations.push_back(1); 

    for (int coin: denominations) { 
     int numCoins = N/coin; 
     N %= coin; 
     if (numCoins > 0) 
      std::cout << numCoins << " x " << coin << '\n'; 
    } 

    return 0; 
} 

现场演示:http://ideone.com/h2SIHs

+0

嗯什么是size_t denomCount; ?是检查大小?我尝试过矢量,但我对它没有很好的理解,所以我想再次尝试一下 – Darkflame

+0

@Darkflame denomCount是用户要输入的教派数量,'size_t'“可以存储理论上的最大尺寸任何类型的可能对象(包括数组)“(http://en.cppreference.com/w/cpp/types/size_t)所以这是标准库容器,如std :: vector用于传递/返回大小 - 它是vector :: size()'的返回类型 – kfsone