UVA 11340-报纸不接受答案



我在OnlineJudge.org上为问题11340做了一个解决方案(https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2315),问题很简单,阅读一篇文章,并根据每个字符的价格列表确定其成本。

我在给定的测试中得到正确的输出,也在https://www.udebug.com/UVa/11340上找到的额外测试中得到正确的输出,但是我的代码在裁判上抛出错误的答案。这不是我第一次在这个页面上遇到这样的情况:一个可以工作的代码由于完全无关的原因而不被接受(例如,使用cin但使用scanf时代码不被接受)

下面是代码

#include <iostream>
#include <string>
#include <cstdio>
//#include <fstream>
using namespace std;
//Idea: Store the values on a positional array where their position is determined by 
//its ASCII value, then just read the article and calculate add the costs up.
int main(){
int t;
scanf("%d",&t);
while(t--){
float cost = 0.0;//Final cost
int K; cin>>K;//How many characters with value will exist
int char_costs[300] = {0};//We set the ASCII value of the character as the position, 
//and inside how much it costs
//300 just to be safe, but 128 must have been perhaps enough (amount of ascii values)
char character;
for(int i = 0; i < K; i++){
cin>>character;//read the character
cin>>char_costs[(int)character];//save the cost of that character on its ASCII value postion
}
int M; cin>>M;//Read how many lines of a given article to read
string current_line;//Current line of the article
for(int i = 0; i <= M; i++){
getline(cin,current_line);//read the line
for(int current_char = 0; current_char <= current_line.length(); current_char++){//Go through each character of the current line
cost += char_costs[current_line[current_char]];//Add the cost of that character (if it wasn't given then it's zero)
}
}
cost /= 100.0;//Divde the cost by 100 (since we are given costs in cents)
printf("%.2lf$n",cost);//print it
}
}

char的取值范围是[-128, 127]
但是,输入可能包含[0, 255]范围内的扩展ASCII字符

例如,我们得到如下的输入行:
© 100

字符©的码位为169。

char character;
cin >> character; //get ©
//character = 169 (exceed 127)
//so, character is converted to -87

您的表是:int char_costs[300]

char_costs[(int)character] 
= char_costs[-87], out of range of array.

我们可以像下面这样声明char_costs:

map<int, int> char_costs

希望这对你有帮助:)

相关内容

  • 没有找到相关文章

最新更新