我試圖在編碼網站上解決一個簡單的問題。我必須找到一個陣列中有多少對可以被給定的整數 k 整除。下面代碼中的邏輯很糟糕,我后來得到了 100p,但是我在糟糕的代碼中發現了一個奇怪的錯誤。
這里是:
#include <bits/stdc .h>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
vector<string> split(const string &);
int divisibleSumPairs(int n, int k, vector<int> ar) {
int modK[k] = {0};
for(int i = 0; i < n; i)
modK[ar[i] % k];
int cnt = 0;
///cout << modK[0] << '\n'; <- If I uncomment this, the output is 1
cnt = modK[0] * ((modK[0]) - 1) / 2;
if(k % 2 == 0)
cnt = (modK[k / 2] * (modK[k / 2] - 1)) / 2;
else
for(int i = 0; i < k / 2; i)
cnt = modK[i] * modK[k - i];
return cnt;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string first_multiple_input_temp;
getline(cin, first_multiple_input_temp);
vector<string> first_multiple_input = split(rtrim(first_multiple_input_temp));
int n = stoi(first_multiple_input[0]);
int k = stoi(first_multiple_input[1]);
string ar_temp_temp;
getline(cin, ar_temp_temp);
vector<string> ar_temp = split(rtrim(ar_temp_temp));
vector<int> ar(n);
for (int i = 0; i < n; i ) {
int ar_item = stoi(ar_temp[i]);
ar[i] = ar_item;
}
int result = divisibleSumPairs(n, k, ar);
fout << result << "\n";
fout.close();
return 0;
}
string ltrim(const string &str) {
string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
);
return s;
}
string rtrim(const string &str) {
string s(str);
s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end()
);
return s;
}
vector<string> split(const string &str) {
vector<string> tokens;
string::size_type start = 0;
string::size_type end = 0;
while ((end = str.find(" ", start)) != string::npos) {
tokens.push_back(str.substr(start, end - start));
start = end 1;
}
tokens.push_back(str.substr(start));
return tokens;
}
如果我注釋掉cout << modK[0] << '\n';,輸出(在輸出檔案中,不在螢屏上)是 65141,如果我不注釋,它是 1。為什么?這就是問題:
https://www.hackerrank.com/challenges/three-month-preparation-kit-divisible-sum-pairs/problem?h_l=interview&playlist_slugs[]=preparation-kits&playlist_slugs[]=three-month-preparation- kit&playlist_slugs[]=三個月一周一
uj5u.com熱心網友回復:
modK[k - i]當i為 0時,訪問越界modK[k - i - 1]。這應該是。
uj5u.com熱心網友回復:
在 C 中,陣列的大小必須是編譯時常量。所以你不能寫這樣的代碼:
int n = 10;
int arr[n]; //incorrect
正確的寫法是:
const int n = 10;
int arr[n]; //correct
出于同樣的原因,以下陳述句在您的代碼中不正確:
int modK[k] = {0}; //incorrect because k is a function parameter
也看看:為什么我不應該#include <bits/stdc .h>
您還可以/應該使用除錯器來檢查索引的值,看看您是否正在嘗試訪問陣列的越界元素。這是未定義行為的常見原因。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/317343.html
上一篇:通過可變引數修改陣列
