C++基本程序运行时错误

C++ Basic Program Runtime Error

本文关键字:运行时错误 程序 C++      更新时间:2023-10-16

我正在为open.kattis编程网站编写一个非常简单的程序。这是他们网站上最容易出现的问题之一,所以这对我的自尊心很打击。当我自己测试代码时,它工作得很好,但它们的结果表明我在未知的测试用例中遇到了运行时错误。问题描述的链接是: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]对于这个练习是不够的:

行程次数最多为100,并且任何城市名称包含的字符数都不超过20

将可能的城市数量称为"旅行"有点误导,但这不是测试的数量(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;
}