本地解与牛客解不一致的问题
兄弟们,我有一个小问题求教,为什么我的代码,在本地结果完全正确,在牛客网上提交之后结果就变样了呀!
本地测试正确,但是在牛客网上提交后就成了另一个答案。比如 888188就变成了666166;
题目如下:
拼多多2019年套题第1题
A 国的手机号码由且仅由 N 位十进制数字(0-9)组成。一个手机号码中有至少 K 位数字相同则被定义为靓号。A 国的手机号可以有前导零,比如 000123456 是一个合法的手机号。 小多想花钱将自己的手机号码修改为一个靓号。修改号码中的一个数字需要花费的金额为新数字与旧数字之间的差值。比如将 1 修改为 6 或 6 修改为 1 都需要花 5 块钱。 给出小多现在的手机号码,问将其修改成一个靓号,最少需要多少钱?
//先用hash表得到需要转换的数字数量。
//再依次从非当前数字中找出所需数量进行转换,并记录花费
#include<iostream>
#include<vector>
#include<string>
#include<unordered_map>
#include<algorithm>
#include<set>
using namespace std;
int getAns(unordered_map<int,int>m,int num,int k,unordered_map<char,vector<int>>local,string& res)
{
int i = 1;
int cost=0;
while (i<10&&k>0)
{
if (m.count(num - i))
{
if (k > m[num - i])
{
k -= m[num - i];
cost += m[num - i]*i;
for (int j = 0; j < local[num - i + '0'].size(); ++j)
{
res[local[num-i+'0'][j]] = (num+'0');
}
}
else
{
cost += k * i;
for (int j = local[num-i+'0'].size()-1; j>=0&&k>0; --k,--j)
res[local[num-i+'0'][j]] = (num+'0');
}
}
if (m.count(num + i))
{
if (k > m[num + i])
{
k -= m[num + i];
cost += m[num + i] * i;
for (int j = 0; j < local[num + i + '0'].size(); ++j)
res[local[num+i+'0'][j]] = (num+'0');
}
else
{
cost += k * i;
for (int j = 0; j < local[num + i + '0'].size() && k>0; --k,++j)
res[local[num+i+'0'][j]] = (num+'0');
}
}
++i;
}
if (k == 0)
return cost;
else
return 2147483647;
}
int main()
{
int N = 0;
int K = 0;
string Result={};
while (cin >> N >> K)
{
if (N < K)
return 0;
string str;
cin >> str;
unordered_map<int, int>m;
unordered_map<char, vector<int>> local;
for (int i = 0; i < str.size(); ++i)
{
m[str[i] - '0']++;
local[str[i]].push_back(i);
}
int cost = 2147483647;
string tmpRes = str;
Result = str;
set<string> Res;
for (auto it = m.begin(); it != m.end(); ++it)
{
int tmp = K - it->second;
if (tmp <= 0)
{
std::cout << 0 << std::endl;
std::cout << str << std::endl;
return 0;
}
tmpRes = str;
int tmpCost = getAns(m, it->first, tmp, local, tmpRes);
if (tmpCost <= cost)
{
cost = tmpCost;
if (tmpRes < Result)
{
Result.clear();
Result = {tmpRes.begin(),tmpRes.end()};
}
}
}
std::cout << cost << std::endl;
std::cout << Result << std::endl;
}
return 0;
}
正面是本地的测试及输出:
