前缀和与差分

海底高铁

题目描述

该铁路经过 N N N 个城市,每个城市都有一个站。不过,由于各个城市之间不能协调好,于是乘车每经过两个相邻的城市之间(方向不限),必须单独购买这一小段的车票。第 i i i 段铁路连接了城市 i i i 和城市 i + 1 ( 1 ≤ i < N ) i+1(1\leq i<N) i+1(1i<N)。如果搭乘的比较远,需要购买多张车票。第 i i i 段铁路购买纸质单程票需要 A i A_i Ai 博艾元。

虽然一些事情没有协调好,各段铁路公司也为了方便乘客,推出了 IC 卡。对于第 i i i 段铁路,需要花 C i C_i Ci 博艾元的工本费购买一张 IC 卡,然后乘坐这段铁路一次就只要扣 B i ( B i < A i ) B_i(B_i<A_i) Bi(Bi<Ai) 元。IC 卡可以提前购买,有钱就可以从网上买得到,而不需要亲自去对应的城市购买。工本费不能退,也不能购买车票。每张卡都可以充值任意数额。对于第 i i i 段铁路的 IC 卡,无法乘坐别的铁路的车。

Uim 现在需要出差,要去 M M M 个城市,从城市 P 1 P_1 P1 出发分别按照 P 1 , P 2 , P 3 , ⋯   , P M P_1,P_2,P_3,\cdots,P_M P1,P2,P3,,PM 的顺序访问各个城市,可能会多次访问一个城市,且相邻访问的城市位置不一定相邻,而且不会是同一个城市。

现在他希望知道,出差结束后,至少会花掉多少的钱,包括购买纸质车票、买卡和充值的总费用。

输入格式

第一行两个整数, N , M N,M N,M

接下来一行, M M M 个数字,表示 P i P_i Pi

接下来 N − 1 N-1 N1 行,表示第 i i i 段铁路的 A i , B i , C i A_i,B_i,C_i Ai,Bi,Ci

输出格式

一个整数,表示最少花费

样例 #1

样例输入 #1

9 10
3 1 4 1 5 9 2 6 5 3
200 100 50
300 299 100
500 200 500
345 234 123
100 50 100
600 100 1
450 400 80
2 1 10

样例输出 #1

6394

提示

2 2 2 3 3 3 以及 8 8 8 9 9 9 买票,其余买卡。

对于 30 % 30\% 30% 数据 M = 2 M=2 M=2

对于另外 30 % 30\% 30% 数据 N ≤ 1000 , M ≤ 1000 N\leq1000,M\leq1000 N1000M1000

对于 100 % 100\% 100% 的数据 M , N ≤ 1 0 5 , A i , B i , C i ≤ 1 0 5 M,N\leq 10^5,A_i,B_i,C_i\le10^5 M,N105Ai,Bi,Ci105


import java.io.*;
import java.util.*;

public class Main {
	
	static int N = 100010;
	static int cnt[] = new int[N], a[] = new int[N], c[] = new int[N], b[] = new int[N], p[] = new int[N];
	static int n, m;
	static long ans;
	
	public static void main(String[] args) throws IOException{
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StreamTokenizer stmInput = new StreamTokenizer(br);
		stmInput.nextToken();
		n = (int)stmInput.nval;
		stmInput.nextToken();
		m = (int)stmInput.nval;
		for(int i = 1; i <= m; i++) {
			stmInput.nextToken();
			p[i] = (int)stmInput.nval;
		}
		
		for(int i = 1; i < n; i++) {
			stmInput.nextToken();
			a[i] = (int)stmInput.nval;
			stmInput.nextToken();
			b[i] = (int)stmInput.nval;
			stmInput.nextToken();
			c[i] = (int)stmInput.nval;
		}
		
		// 差分一下每段路要走多少次
		for(int i = 1; i < m; i++) {
			// 注意这里给的路径顺序是无序的,差分时要注意一下
			int min = Math.min(p[i], p[i+1]), max = Math.max(p[i], p[i+1]);
			cnt[min] += 1;
			cnt[max] -= 1;
		}
		// 求出每段路走多少次
		for(int i = 1; i < n; i++) {
			cnt[i] += cnt[i-1];
		}
		
		for(int i = 1; i < n; i++) {
			// 记得开long
			long tmp1 = (long)a[i] * cnt[i], tmp2 = c[i] + (long)b[i] * cnt[i];
			ans += Math.min(tmp1, tmp2);
		}
		System.out.println(ans);
		
		br.close();
	}
	
	
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值