每日一题之692. G巴士计数

内容

 

输入样例:

2
4
15 25 30 35 45 50 10 20
2
15
25

10
10 15 5 12 40 55 1 10 25 35 45 50 20 28 27 35 15 40 4 5
3
5
10
27

输出样例:

Case #1: 2 1
Case #2: 3 3 4

样例解释

 

0727自写代码--暴力

#include<iostream>
using namespace std;
const int M=510;
int T,N,CityA[M],CityB[M],x;

int main(){
	cin>>T;//几组数据 
	int n;
	for(int t=1;t<=T;t++){
		cin>>N;//G巴士的数量 
		for(int i=0;i<N;i++){
			cin>>CityA[i]>>CityB[i];//城市编号 
		}
		cin>>n;//询问数量 
		cout<<"Case #"<<t<<":";
		while(n--){
		    int ans=0;
			cin>>x;//询问城市的编号 
			
//核心代码:
			for(int j=0;j<N;j++)
			if(x>=CityA[j]&&x<=CityB[j])
			ans++;
			cout<<ans<<" ";
		}
		cout<<endl;
	}
	return 0;
} 

方法二 差分
我们是否能通过这些巴士的服务范围而一次性得到所有城市的巴士数量呢
对一段序列{0, 0, 0, 0, 0}, 如果我们想让它第二到第四个元素都加个1, 我们可以让第二个元素+1, 第五个元素-1,得到{0, 1, 0, 0, -1}, 再对它求一遍前缀和, 就可以得到{0, 1, 1, 1, 0}. 这就是差分的基本思想

本题几乎是裸差分问题, 对于每个巴士的服务范围[l, r], 我们在差分数组中令count[l] += 1, count[r+1]-=1即可, 最后将所有的巴士范围都插入到差分数组中后, 求一遍前缀和, 即为所有城市的巴士数量

时间复杂度:O(A), A为城市总数, 在题中固定为5000

#include <bits/stdc++.h>

using namespace std;

int main() {
    int count[5010];
    int T, N, P, C;
    int i, j, k;
    int l, r;

    cin >> T;
    for(i=1; i<=T; i++)
    {
        memset(count, 0, sizeof count);
        cin >> N;

        //构造差分数组
        for(j=0; j<N; j++)
        {
            cin>> l >> r;
            count[l]++;
            count[r+1]--;
        }

        //求前缀和
        for(j=2; j<=5001; j++) count[j] += count[j-1];

        cin >> P;
        cout << "Case #" << i << ":";
        while(P--)
        {
            cin >> C;
            cout << " " << count[C];
        }

        cout << endl;
    }

    return 0;
}

法二转载自(作者:trudbot
链接:https://www.acwing.com/solution/content/122001/)
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值