C++ 基本程序运行时错误
C++ Basic Program Runtime Error
我正在为 open.kattis 编程网站编写一个非常简单的程序。这是他们网站上最简单的问题之一,因此对我的自尊心造成了很大的打击。当我自己测试代码时它工作正常,但他们的结果表明我在未知测试用例上遇到运行时错误。问题描述的 link 是:https://open.kattis.com/problems/everywhere 但问题的一般基础是我试图确定字符串列表中唯一实例的数量
我的代码是:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
short t; // test cases
short trips;
char city[21];
char cities[50][21];
bool found;
short count;
// read in the number of test cases
cin >> t;
// loop through each test case
for(int i=0; i<t; i++)
{
// read in the number of trips taken
cin >> trips;
// reset the count to 0
count = 0;
// loop through each trip
for(int j=0; j<trips; j++)
{
// read in the city
cin >> city;
// Linear search to determine if city has been visited
found = false;
for(int k=0; k<count; k++)
{
if(strcmp(city, cities[k]) == 0)
found = true;
}
// If city hasn't been visted, increment count and add to list
if(!found)
{
strcpy(cities[count], city);
count++;
}
}
// Output results for test case
cout << count << endl;
}
return 0;
}
您误读了描述。 char cities[50][21]
不足以完成此练习:
The number of trips is at most 100 and no city name contains more than 20 characters.
这里称可能的城市数"trips"有点误导,但这不是测试的数量(T≤50)。话虽如此,如果您将关注点分开并实际使用 C++ 标准库,您可以大大改进您的程序:
#include <iostream>
#include <set> // <- Hint: those both will help you tremendously!
#include <string> // <-
int single_test_case(){
// ...
}
int main(){
int tests;
std::cin >> tests;
for(int i = 0; i < tests; ++i){
std::cout << single_test_case();
}
return 0;
}
我正在为 open.kattis 编程网站编写一个非常简单的程序。这是他们网站上最简单的问题之一,因此对我的自尊心造成了很大的打击。当我自己测试代码时它工作正常,但他们的结果表明我在未知测试用例上遇到运行时错误。问题描述的 link 是:https://open.kattis.com/problems/everywhere 但问题的一般基础是我试图确定字符串列表中唯一实例的数量
我的代码是:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
short t; // test cases
short trips;
char city[21];
char cities[50][21];
bool found;
short count;
// read in the number of test cases
cin >> t;
// loop through each test case
for(int i=0; i<t; i++)
{
// read in the number of trips taken
cin >> trips;
// reset the count to 0
count = 0;
// loop through each trip
for(int j=0; j<trips; j++)
{
// read in the city
cin >> city;
// Linear search to determine if city has been visited
found = false;
for(int k=0; k<count; k++)
{
if(strcmp(city, cities[k]) == 0)
found = true;
}
// If city hasn't been visted, increment count and add to list
if(!found)
{
strcpy(cities[count], city);
count++;
}
}
// Output results for test case
cout << count << endl;
}
return 0;
}
您误读了描述。 char cities[50][21]
不足以完成此练习:
The number of trips is at most 100 and no city name contains more than 20 characters.
这里称可能的城市数"trips"有点误导,但这不是测试的数量(T≤50)。话虽如此,如果您将关注点分开并实际使用 C++ 标准库,您可以大大改进您的程序:
#include <iostream>
#include <set> // <- Hint: those both will help you tremendously!
#include <string> // <-
int single_test_case(){
// ...
}
int main(){
int tests;
std::cin >> tests;
for(int i = 0; i < tests; ++i){
std::cout << single_test_case();
}
return 0;
}