跳到正文

个人记录

P5661 [CSP-J2019] 公交换乘 深度题解

Callum_Zbq约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年1月20日
收录
2026年10月2日
更新
2026年11月15日
篇幅
约 4 分钟

版本

  1. v1当前

原题链接

此题是模拟好题, 有许多细节需要考虑

解题思路

  • 读题, 题目还是很好理解的, 关键就是优惠券的使用, 还有时间的处理
  • 我们可以想到直接模拟

代码思路

  • 定义一个二维数组ff

  • 如果坐地铁

    f[i][1]f[i][1] 为 价格, f[i][2]f[i][2] 为 时间 f[i][3]f[i][3] 为有无优惠券

    C++
    if (by == 0) //如果坐地铁 
      {
      	discounts ++; //新增一张优惠券 
      	f[discounts][1] = price;
      	f[discounts][2] = time;
      	f[discounts][3] = 1;
      	answer += f[discounts][1]; //金额相加
      } 
  • 如果坐公交 先过滤掉过期的券, 枚举有用的券

    C++
    else // 如果坐公交 
      {
      	while (f[d][2] + 45 < time) d++; // 去掉没用的优惠券 
      	for (int j = d; j <= discounts; j++) 
      	{
        if (f[j][2] + 45 >= time && f[j][1] >= price && f[j][3])  
      	// 如果在有限期内,并且地铁金额大于公交金额  
      		{
        		fb = true; 
        		f[j][3] = 0;  
        		// 用了优惠券 
        		break; 
            }
      	}
      	if (fb == false) // 没用上优惠券 
      	{
    		answer += price;
      }
      }

    AC代码

    C++
    #include<iostream>
    #define LL long long
    
    using namespace std;
    
    template<typename T>
    void read(T &x){
        bool f = 1; x = 0;
    	char ch = getchar();
        while (ch < '0' || ch > '9'){ if (ch == '-') f = !f; ch = getchar(); }
        while (ch >= '0' && ch <= '9'){ x = (x << 1) + (x << 3) + (ch ^ 48); ch=getchar(); }
        x = (f ? x: -x);return;
    }
    
    const LL N = 1e5 + 10;
    
    LL n_subway,n_bus,d = 1;
    
    LL f[N][4];
    LL n,answer,discounts;
    
    int main()
    {	
    	read(n);
    	for (int i = 1; i <= n; i ++) 
    	{
    		bool fb=false;
    		LL by,price,time;
    		read(by); read(price); read(time);
    		if (by == 0) //如果坐地铁 
    		{
    			discounts ++; //新增一张优惠券 
    			f[discounts][1] = price;
    			f[discounts][2] = time;
    			f[discounts][3] = 1;
    			answer += f[discounts][1]; //金额相加
    		} 
    		else // 如果坐公交 
    		{
    			while (f[d][2] + 45 < time) d++; // 去掉没用的优惠券 
    			for (int j = d; j <= discounts; j++) 
    			{
    				if (f[j][2] + 45 >= time && f[j][1] >= price && f[j][3])  
    				// 如果在有限期内,并且地铁金额大于公交金额  
    				{
    					fb = true; 
    					f[j][3] = 0;  
    					// 用了优惠券 
    					break; 
    				}
    			}
    			if (fb == false) // 没用上优惠券 
    			{
    				answer += price;
    			}
    		}
    	}
    	cout << answer ;
    	return 0;
    } 

我是zhaobingquan2030, 如有建议, 请指出!

原文