E - Two Switches

Problem Statement

Alice and Bob are controlling a robot. They each have one switch that controls the robot.
Alice started holding down her button A second after the start-up of the robot, and released her button B second after the start-up.
Bob started holding down his button C second after the start-up, and released his button D second after the start-up.
For how many seconds both Alice and Bob were holding down their buttons?

Constraints

  • 0A<B100
  • 0C<D100
  • All input values are integers.
Input

Input is given from Standard Input in the following format:

A B C D
Output

Print the length of the duration (in seconds) in which both Alice and Bob were holding down their buttons.

Sample Input 1

0 75 25 100
Sample Output 1

50

Alice started holding down her button 0 second after the start-up of the robot, and released her button 75 second after the start-up.
Bob started holding down his button 25 second after the start-up, and released his button 100 second after the start-up.
Therefore, the time when both of them were holding down their buttons, is the 50seconds from 25 seconds after the start-up to 75 seconds after the start-up.

Sample Input 2

0 33 66 99
Sample Output 2

0

Alice and Bob were not holding their buttons at the same time, so the answer is zero seconds.

思路:画出一个数轴,然后把Alice和Bob的按按钮的时间段标上去,然后求公共的那部分就可以了。

#include
#include
using namespace std;
int main()
{
int a, b, c, d;
int sum;
cin >> a >> b >> c >> d;
if (b < c || d < a)
sum = 0;
else
{
sum = min(b, d) - max(a, c);
}
cout << sum << endl;
return 0;
}

你可能感兴趣的:(平时学习对应知识点练习题)