我做算法题的时候需要数据类型long long类型,数据个数int类型,我用vector总是结果错误,使用数组就可以正确AC,这是不是和vector的某种特性有关呢?
题目:求数组中逆序对的个数
代码(结果错误的,但是我自己测试的是对的)
#include<iostream>
#include<vector>
#include<fstream>
using namespace std;
vector<int>input;
vector<int>now;
long long mergesort(int left, int right) {
now.clear();
if (left >= right)return 0;
int mid = (left + right) / 2;
long long res = mergesort(left, mid) + mergesort(mid+1, right);
int i = left,j = mid + 1, k = 0;
while (i <= mid && j <= right) {
if (input[i] <= input[j]) {
now.push_back(input[i]); k++; i++;
}
else {
now.push_back(input[j]);
k++; j++;
res += mid - i + 1;
}
}
while (i <= mid) { now.push_back(input[i]); i++; k++; }
while (j <= right) { now.push_back(input[j]); k++; j++; }
for (int i = left, j = 0; i <= right&&j<=k; i++, j++) {
input[i] = now[j];
}
return res;
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int now;
scanf("%d", &now);
input.push_back(now);
}
printf("%lld", mergesort(0, n - 1));
return 0;
}
代码(AC的)
#include<iostream>
#include<vector>
#include<fstream>
using namespace std;
int input[500003];
int now[500003];
long long mergesort(int left, int right) {
if (left >= right)return 0;
int mid = (left + right) >> 1;
long long res = mergesort(left, mid) + mergesort(mid+1, right);
int i = left,j = mid + 1, k = 0;
while (i <= mid && j <= right) {
if (input[i] <= input[j]) {
//now.push_back(input[i]); k++; i++;
now[k++]=input[i++];
}
else {
//now.push_back(input[j]);
now[k++]=input[j++];
//k++; j++;
res += mid - i + 1;
}
}
while (i <= mid) {
//now.push_back(input[i]); i++; k++;
now[k++]=input[i++];
}
while (j <= right) {
//now.push_back(input[j]); k++; j++;
now[k++]=input[j++];
}
for (int i = left, j = 0; i <= right&&j<=k; i++, j++) {
input[i] = now[j];
}
return res;
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d",&input[i]);
}
printf("%lld", mergesort(0, n - 1));
return 0;
}