topic
The server has three operating states: no-load, single-task, and multi-task, and the energy consumption of each time slice is 1, 3, and 4 respectively;
Each task is defined by a start time slice and an end time slice:
If only one task needs to be executed in a time slice, the server is in a single-task state;
If there are multiple tasks to be executed in a time slice, the server is in a multi-tasking state;
Given a list of tasks, please calculate the total energy consumption of the server from the start of the first task to the end of all tasks.
train of thought
Use the difference array to solve, first construct the difference array, then restore it to the real array, and traverse the time slice
the code
num = int(input())
dif = [0] * 100001
min_value,max_value = 10000,-1
for i in range(num):
l,r = map(int,input().split(" "))
min_value = min(min_value,l)
max_value = max(max_value,r)
dif[l]+=1
dif[r+1]-=1
time = [0] * (max_value+1)
time[0] = dif[0]
for i in range(1,max_value+1):
time[i] += time[i-1]+dif[i]
ans = 0
for i in range(min_value,max_value+1):
if time[i]==0:
ans += 1
elif time[i]==1:
ans += 3
else:
ans += 4
print(ans)
# 测试1
# 3
# 4 8
# 1 6
# 2 9
# 测试2
# 2
# 2 5
# 8 9