測試執行都顯示沒問題
但是跑題目卻TLE
求解
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int gcd(int a,int b) {
if (a == 0)
return b;
if (a > b)
return gcd(a % b, b);
else
return gcd(b, a);
}
int main() {
int num;
cin >> num;
cin.ignore();
for (int i = 0; i < num; i++) {
int A[100];
int count = 0;
string input2;
getline(cin,input2);
int temp = 0;
for (int j = 0; j < input2.length(); j++) {
if (input2[j] >= '0' && input2[j] <= '9') {
temp = temp * 10 + input2[j] - '0';
}
else {
A[count] = temp;
temp = 0;
count++;
}
}
A[count] = temp;
temp = 0;
count++;
int maxi = 1;
for (int j = 0; j < count; j++)
for (int k = j + 1; k < count; k++)
if (A[j] != 0 && A[k] != 0)
maxi = max(maxi, gcd(A[j], A[k]));
cout << maxi << endl;
}
}
測試執行都顯示沒問題
但是跑題目卻TLE
求解
#include
#include
#include
using namespace std;
int gcd(int a,int b) {
if (a == 0)
return b;
if (a > b)
return gcd(a % b, b);
else
return gcd(b, a);
}
int main() {
int num;
cin >> num;
cin.ignore();
for (int i = 0; i < num; i++) {
int A[100];
int count = 0;
string input2;
getline(cin,input2);
int temp = 0;
for (int j = 0; j < input2.length(); j++) {
if (input2[j] >= '0' && input2[j] <= '9') {
temp = temp * 10 + input2[j] - '0';
}
else {
A[count] = temp;
temp = 0;
count++;
}
}
A[count] = temp;
temp = 0;
count++;
int maxi = 1;
for (int j = 0; j < count; j++)
for (int k = j + 1; k < count; k++)
if (A[j] != 0 && A[k] != 0)
maxi = max(maxi, gcd(A[j], A[k]));
cout << maxi << endl;
}
}
會TLE代表測資的數字很多的時候會超過時間限制喔!可能是演算法的部分不夠快,可以參考其他解題報告的演算法