洛谷P10902回文数组
cpp
#include<iostream>
#include<cmath>
using namespace std;
int n;
const int N = 100010;
int diff[N], a[N];
int main() {
cin >> n;
for (int i = 1; i <= n; i++)cin >> a[i];
for (int i = 1; i <= n / 2; i++) {
diff[i] = a[i] - a[n - i + 1];
}
long long ans = 0;
for (int i = 1; i <= n; i++) {
ans += abs(diff[i]);
if (diff[i] > 0 && diff[i + 1] > 0) {
diff[i + 1] -= min(diff[i], diff[i + 1]);
}
else if (diff[i] < 0 && diff[i + 1] < 0) {
diff[i + 1] -= max(diff[i], diff[i + 1]);
}
}
cout << ans << endl;
return 0;
}
洛谷P10903商品库存管理
cpp
#include <iostream>
#include<vector>
using namespace std;
int n, m;
const int N = 300010;
int a[N], b[N];
typedef pair<int, int> PII;
vector<PII> query;
int main()
{
cin >> n >> m;
for(int i = 1; i <= n; i++){
a[i] = 0;
b[i] = a[i] - a[i - 1];
}
for(int i = 1; i <= m; i++){
int l, r; cin >> l >> r;
query.push_back({l, r});
b[l] += 1;
b[r + 1] -= 1;
}
for(int i = 1; i <= n; i++){
a[i] = b[i] + a[i - 1];
}
int ans = 0;
for(int i = 1; i <= n; i++){
if(a[i] == 0)ans++;
if(a[i] != 1)a[i] = 0;
}
for(int i = 1; i <= n; i++)a[i] += a[i - 1];
for(auto item : query){
cout << ans + a[item.second] - a[item.first - 1] << endl;
}
// 请在此输入您的代码
return 0;
}