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,一只菜鸡

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值