CS Academy Switch the Lights
题目链接:https://csacademy.com/contest/archive/task/switch-the-lights/statement/
题目大意:有N盏灯,0表示灯是灭的,1表示灯亮。每盏灯i操作一次可以更改第i到r[i]盏灯的状态,每个灯的操作花费为C[i].问最小花费。
解题思路:首先我们很快就会发现实际上由于第i盏灯不会影响到之前的灯,因此我们只需要从头到尾判断每盏灯的状态,但是问题在于如何计算一盏灯之前有多少盏灯会影响到这盏灯(editorial里面有solution的)。
朴素的想法就是O(n2),但是仔细思考一下:我们设置一个全局计数器cnt,每次更改灯 i 的状态时cnt++,到达这个灯i的 r[i] 的时候cnt--,那么就可以保证对于一盏灯来说,能够影响它的即是全局计数器的值。那么我们可以用一个数组sum[i]记录这个灯之前,以i为结束的灯的个数。那么对于灯i:
如果 cnt 为奇数 并且 a[i] == 0 或者 cnt 为偶数 并且 a[i] == 1,那么需要更新这个灯 ,cnt++,sum[r[i]]++
然后cnt -= sum[i] ,表示有sum[i]个灯到这个点不再对后续灯产生影响
代码:
1 const int maxn = 1e5 + 10; 2 int n; 3 int a[maxn]; 4 int r[maxn], c[maxn]; 5 int sum[maxn]; 6 7 void solve(){ 8 memset(sum, 0, sizeof(sum)); 9 ll ans = 0; 10 int v = 0; 11 for(int i = 1; i <= n; i++){ 12 if((v & 1) && (a[i]) == 0 || !(v & 1) && (a[i] == 1)){ 13 ans += c[i]; 14 v++; 15 sum[r[i]]++; 16 } 17 v -= sum[i]; 18 } 19 printf("%lld\n", ans); 20 } 21 int main(){ 22 scanf("%d", &n); 23 for(int i = 1; i <= n; i++){ 24 char ch; 25 scanf(" %c", &ch); 26 a[i] = ch == '0'? 0: 1; 27 } 28 for(int i = 1; i <= n; i++) scanf("%d", &r[i]); 29 for(int i = 1; i <= n; i++) scanf("%d", &c[i]); 30 solve(); 31 }
题目:
Switch the Lights
Memory limit: 128 MB
There are NN lightbulbs arranged in a line. For each of them you know whether it's turned on or off.
There are also NN light switches. The i^{th}ith switch toggles the state of all the lightbulbs between ii and R_iRi, and it costs C_iCi to use it.
Find the minimum total cost of switching off all the lightbulbs.
Standard input
The first line contains a single integer NN.
The second line contains a string of length NN. The i^{th}ith character of the string is 0
if initially the i^{th}ith lightbulb is turned off, and 1
if it's turned on.
The third line contains NN integers representing the elements of RR.
The fourth line contains NN integers representing the elements of CC.
Standard output
If there is no solution output -1−1.
Otherwise, print the answer on the first line.
Constraints and notes
- 1 \leq N \leq 10^51≤N≤105
- i \leq R_i \leq Ni≤Ri≤N
- 1 \leq C_i \leq 10^91≤Ci≤109
Input | Output | Explanation |
---|---|---|
4 1010 2 3 3 4 3 1 2 3 |
4 |
|
5 01100 1 2 3 4 5 1 5 5 2 3 |
10 |
|
4 0101 3 4 3 4 1 1 1 1 |
2 |
|