为什么在某些情况下,我在这个问题上会得到TLE?
Why am i getting a TLE in this question on some cases?
https://www.hackerrank.com/challenges/c-class-templates/problem. 这是问题的链接。 我使用了基本模板概念和基本模板专业化。 代码如下:
template<class T>
class AddElements{
T a;
public:
AddElements(T x)
{
a=x;
}
T add(T y)
{
return a+y;
};
};
template<>
class AddElements<string>{
string x;
public:
AddElements(string a)
{
x=a;
}
string concatenate(string b)
{
return x+b;
};
};
int main () {
int n,i;
cin >> n;
for(i=0;i<n;i++) {
string type;
cin >> type;
if(type=="float") {
double element1,element2;
cin >> element1 >> element2;
AddElements<double> myfloat (element1);
cout << myfloat.add(element2) << endl;
}
else if(type == "int") {
int element1, element2;
cin >> element1 >> element2;
AddElements<int> myint (element1);
cout << myint.add(element2) << endl;
}
else if(type == "string") {
string element1, element2;
cin >> element1 >> element2;
AddElements<string> mystring (element1);
cout << mystring.concatenate(element2) << endl;
}
}
return 0;
}
在某些情况下,它给了TLE,我不知道为什么。
您正在按值传递参数。尝试传递常量引用或使用引用。
通常你可以忽略 TLE。这似乎取决于机器的当前工作负载。我运行相同的代码 10 次,每次其他测试用例都使用 TLE 失败。一小时后,所有测试用例都使用相同的代码成功。
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cassert>
using namespace std;
template<class T>
class AddElements{
T a;
public:
AddElements(T x) : a(x) {}
T add(T y) {
return a + y;
}
};
template<>
class AddElements<string>{
string &a;
public:
AddElements(string &x) : a(x) {}
string concatenate(string &y) {
return a.append(y);
}
};
int main () {
int n,i;
cin >> n;
for(i=0;i<n;i++) {
string type;
cin >> type;
if(type=="float") {
double element1,element2;
cin >> element1 >> element2;
AddElements<double> myfloat (element1);
cout << myfloat.add(element2) << endl;
}
else if(type == "int") {
int element1, element2;
cin >> element1 >> element2;
AddElements<int> myint (element1);
cout << myint.add(element2) << endl;
}
else if(type == "string") {
string element1, element2;
cin >> element1 >> element2;
AddElements<string> mystring (element1);
cout << mystring.concatenate(element2) << endl;
}
}
return 0;
}
有了这段代码,现在所有的测试用例都成功了。一小时前,一些测试用例失败了。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 为什么在某些情况下,我在这个问题上会得到TLE?