一、问题分析
Uim需要在多个城市间出差,每段铁路可以选择购买纸质票或IC卡。我们需要计算在访问所有指定城市后,包括购票、买卡和充值在内的最小总花费。
统计每段铁路的使用次数:使用差分数组高效计算
最优决策:对每段铁路,比较IC卡和纸质票的总花费
计算最小总花费:根据使用次数选择更经济的方案
三、完整代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N, M;
cin >> N >> M;
vector<int> P(M);
for(int i = 0; i < M; ++i) {
cin >> P[i];
}
vector<int> diff(N + 2, 0); // 差分数组
// 计算每段铁路的使用次数
for(int i = 1; i < M; ++i) {
int start = min(P[i-1], P[i]);
int end = max(P[i-1], P[i]);
diff[start]++;
diff[end]--;
}
// 计算前缀和得到每段铁路的实际使用次数
vector<int> count(N, 0);
int current = 0;
for(int i = 1; i < N; ++i) {
current += diff[i];
count[i] = current;
}
long long total = 0;
for(int i = 1; i < N; ++i) {
int A, B, C;
cin >> A >> B >> C;
// 比较两种方案的花费
long long paper_cost = (long long)count[i] * A;
long long ic_cost = (long long)count[i] * B + C;
total += min(paper_cost, ic_cost);
}
cout << total << endl;
return 0;
}