Two Switches 题解
1.题目
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
0≤A<B≤100
0≤C<D≤100
All input values are integers.
输入
Input is given from Standard Input in the following format:
A B C D
输出
Print the length of the duration (in seconds) in which both Alice and Bob were holding down their buttons.
- 简而言之就是给你两个时间段,让你求这两个时间段交集的长度
2.为什么没有AC
- 刚开始我这个小机灵鬼想到了6中情况并且依次列出,我们把这两个时间段为A 、B,如下图
并且写下了如下的代码
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a,b,c,d;
cin>>a>>b>>c>>d;
if(b<=c)
{
cout<<"0"<<endl;
}
else if(b>c&&b<=d)
{
cout<<b-c<<endl;
}
else if(b>c&&b>d&&a<c&&a<d)
{
cout<<d-c<<endl;
}
else if(a>c&&a>d)
{
cout<<"0"<<endl;
}
else if(d>a&&d>c&&b>=d)
{
cout<<d-a<<endl;
}
else if(d>a&&d>b&&a>c)
{
cout<<b-a<<endl;
}
return 0;
}
结果WA了,我现在也懒得查为什么,感觉自己是弱智,还不如建一个数组,把每个时间段中的元素赋给数组变化(++),只要数组中存在两次变化(++),那就是重复的时间段,遍历一遍就得。
3.AC代码
#include<bits/stdc++.h>
using namespace std;
int e[110];
int main()
{
int a,b,c,d,sum=0,i;
cin>>a>>b>>c>>d;
for(i=0;i<=110;i++)
{
if(i>=a&&i<b)
e[i]++;
if(i>=c&&i<d)
e[i]++;
}
for(i=0;i<=110;i++)
{
if(e[i]==2)
sum++;
}
cout<<sum<<endl;
}
如果喜欢的话加个关注呗!我是wanna_ac,一只菜鸡