题目描述
本题大致意思就是求一个数组有哪些区间含奇数个负数
算法1
DP Solution
DP[i]
表示以 i
结尾的区间有多少个含奇数个负数
- 则若 xs[i] < 0,则接到 i - 1 含偶数个负数的区间上
- 否则,则接到 i - 1 含奇数个负数的区间上
时间复杂度
O(n)
C++ 代码
#include <iostream>
#include <queue>
#include <map>
#include <set>
#include <functional>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <tuple>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
template <class T>
T read() {
T x;
cin >> x;
return x;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int n = read<int>();
vector<int> xs;
for (int i = 0; i < n; i += 1) { xs.push_back(read<int>()); }
vector<long> dp(xs.size());
dp[0] = xs[0] < 0;
for (int i = 1; i < xs.size(); i += 1) {
dp[i] = xs[i] < 0;
if (xs[i] < 0) {
dp[i] += i - dp[i - 1];
} else {
dp[i] = dp[i - 1];
}
}
long ncnt = 0, pcnt = 0;
for (int i = 0; i < xs.size(); i += 1) {
ncnt += dp[i];
pcnt += i + 1 - dp[i];
}
cout << ncnt << " " << pcnt << endl;
return 0;
}