今日頭條 最大映射

有 n 個字符串,每個字符串都是由 A-J 的大寫字符構成。現在你將每個字符映射爲一個 0-9 的數字,不同字符映射爲不同的數字。這樣每個字符串就可以看做一個整數,唯一的要求是這些整數必須是正整數且它們的字符串不能有前導零。現在問你怎樣映射字符才能使得這些字符串表示的整數之和最大?

輸入描述:
每組測試用例僅包含一組數據,每組數據第一行爲一個正整數 n , 接下來有 n 行,每行一個長度不超過 12 且僅包含大寫字母 A-J 的字符串。 n 不大於 50,且至少存在一個字符不是任何字符串的首字母。

輸出描述:
輸出一個數,表示最大和是多少。

輸入例子:
2
ABC
BCA

輸出例子:
1875

解答

#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct Element {
    long long weight;
    bool Positive;//不能爲0
    char value;
    int num;
};
int cmp(const void *a, const void *b)
{
    return (*(Element *)a).weight < (*(Element *)b).weight;
}
int main()
{

    Element elem[10];
    for (int i = 0; i < 10; i++)
    {
        elem[i].weight = 0;
        elem[i].Positive = false;//初始化爲可以爲0
        elem[i].value = '0';//表示的字符
        elem[i].num = 0;//對應的數字
    }


    vector<string> temp;
    /*int n;
    cin >> n;*/
    string s;
    /*while (cin >> s)
    {
        temp.push_back(s);
    }*/
    int n = 2;
    temp.push_back("ABC");
    temp.push_back("BCA");
    temp.push_back("EBCA");
    temp.push_back("DBCAE");
    for (int j = 0; j < temp.size(); j++)
    {
        s = temp[j];
        int len = s.length();
        if (len == 0) continue;
        for (int i = 0; i < len; i++)
        {
            elem[s[i] - 'A'].weight = elem[s[i] - 'A'].weight + pow(10, len-i-1);
            if (i == 0)
                elem[s[i] - 'A'].Positive = true;//如果是第一個,肯定不能爲0
            elem[s[i] - 'A'].value = s[i];
        }
    }
    qsort(elem, temp.size(), sizeof(elem[0]), cmp);

    for (int j = 0; j < 10; j++)
    {
        if (elem[j].weight>0)
        {
            if (j == 9 && elem[j].Positive == true)
            {
                elem[j].num = elem[j - 1].num;//第八個第九個交換
                elem[j - 1].num = 0;
            }
            else
                elem[j].num = 9 - j;
        }   
    }
    long long sum = 0;
    for (int j = 0; j<temp.size(); j++)
    {
        s = temp[j];
        int len = s.length();
        if (len == 0) continue;
        for (int i = 0; i < len; i++)
        {
            for (int k = 0; k < 10; k++)
            {
                if (elem[k].value == s[i])
                    sum = sum + elem[k].num*pow(10, len - i - 1);
                else
                    continue;
            }
        }
    }
    cout << sum << endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章