PAT刷题:1016. Phone Bills (25)

本文介绍了一个长话费计算程序的设计与实现。该程序能够根据输入的电话记录和费率结构,计算出每位客户的月度账单。通过解析电话记录的时间戳,并匹配相应的费率,最终输出每位客户的通话详情及总费用。

本题有个大坑:如果客户A的账单记录没有任何一对是合法的,则客户A什么信息都不输出,对于这一点,出题者不说明,也不容易测试出来,我只想问候他全家。

判读有效记录,只要本条记录是on-line,下一条记录是off-line,就是有效记录

先计算出两头零碎时间,再计算出中间通话多少小时,用循环相乘得到结果


A long-distance telephone company charges its customers by the following rules:

Making a long-distance call costs a certain amount per minute, depending on the time of day when the call is made. When a customer starts connecting a long-distance call, the time will be recorded, and so will be the time when the customer hangs up the phone. Every calendar month, a bill is sent to the customer for each minute called (at a rate determined by the time of day). Your job is to prepare the bills for each month, given a set of phone call records.

Input Specification:

Each input file contains one test case. Each case has two parts: the rate structure, and the phone call records.

The rate structure consists of a line with 24 non-negative integers denoting the toll (cents/minute) from 00:00 - 01:00, the toll from 01:00 - 02:00, and so on for each hour in the day.

The next line contains a positive number N (<= 1000), followed by N lines of records. Each phone call record consists of the name of the customer (string of up to 20 characters without space), the time and date (mm:dd:hh:mm), and the word "on-line" or "off-line".

For each test case, all dates will be within a single month. Each "on-line" record is paired with the chronologically next record for the same customer provided it is an "off-line" record. Any "on-line" records that are not paired with an "off-line" record are ignored, as are "off-line" records not paired with an "on-line" record. It is guaranteed that at least one call is well paired in the input. You may assume that no two records for the same customer have the same time. Times are recorded using a 24-hour clock.

Output Specification:

For each test case, you must print a phone bill for each customer.

Bills must be printed in alphabetical order of customers' names. For each customer, first print in a line the name of the customer and the month of the bill in the format shown by the sample. Then for each time period of a call, print in one line the beginning and ending time and date (dd:hh:mm), the lasting time (in minute) and the charge of the call. The calls must be listed in chronological order. Finally, print the total charge for the month in the format shown by the sample.

Sample Input:
10 10 10 10 10 10 20 20 20 15 15 15 15 15 15 15 20 30 20 15 15 10 10 10
10
CYLL 01:01:06:01 on-line
CYLL 01:28:16:05 off-line
CYJJ 01:01:07:00 off-line
CYLL 01:01:08:03 off-line
CYJJ 01:01:05:59 on-line
aaa 01:01:01:03 on-line
aaa 01:02:00:01 on-line
CYLL 01:28:15:41 on-line
aaa 01:05:02:24 on-line
aaa 01:04:23:59 off-line
Sample Output:
CYJJ 01
01:05:59 01:07:00 61 $12.10
Total amount: $12.10
CYLL 01
01:06:01 01:08:03 122 $24.40
28:15:41 28:16:05 24 $3.85
Total amount: $28.25
aaa 01
02:00:01 04:23:59 4318 $638.80

Total amount: $638.80

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <functional>
#include <numeric>
#include <vector>
#include <list>
#include <map>
#include <string>
#include <queue>

using namespace std;

struct Record{
    string name;
    string time;
    string month;
    string date;
    int day;
    int hour;
    int minute;
    string tag;
    Record() : name("") , time("") , tag(""){}
    Record(string _name , string _time , string _tag) : name(_name) , time(_time) , tag(_tag) {
        month=time.substr(0,2);
        date=time.substr(3);
        day = atoi(time.substr(3,2).c_str());
        hour = atoi(time.substr(6,2).c_str()) ;
        minute=atoi(time.substr(9,2).c_str());
    }

    bool operator < (const Record &x)const {
        if(name != x.name)return name<x.name;
        else if(month !=x.month)return month<x.month;
        else if(day !=x.day)return day<x.day;
        else if(hour!=x.hour)return hour < x.hour;
        else if(minute != x.minute)return minute < x.minute;
    }

    int getTicks(){return (day*1440+hour*60+minute);}
};

int rate[24]={0};

int main()
{
    for(int i=0;i<24;i++)cin>>rate[i];
    int cnt=0;
    vector<Record> records;
    cin>>cnt;
    records.reserve(cnt);
    for(int i=0;i<cnt;i++){
        string _name , _time , _tag;
        cin>>_name>>_time>>_tag;
        records.push_back(Record(_name , _time , _tag));
    }
    sort(records.begin() , records.end());
    while(records.size()!=0){
        vector<Record> tRecords;
        double totalCost=0.0;
        string selectName=records.front().name;
        string seletcMonth=records.front().month;
        int index=0;
        while(index < records.size() && records[index].name==selectName &&records[index].month==seletcMonth){
            tRecords.push_back(records[index]);
            index++;
        }
        records.erase(records.begin() , records.begin() + index);
        bool isPrinted=false;
        for(int i=0;i<tRecords.size()-1;i++){
            if(tRecords[i].tag=="on-line" && tRecords[i+1].tag=="off-line"){
                if(isPrinted==false) {cout<<selectName<<" "<<seletcMonth<<endl; isPrinted=true;}
                int tick1=tRecords[i].getTicks();
                int tick2=tRecords[i+1].getTicks();
                int ticks=tick2-tick1;
                cout<<tRecords[i].date<<" "<<tRecords[i+1].date<<" "<<ticks<<" $";
                double cost=0.0;
                if( ticks<=60 && tRecords[i].hour==tRecords[i+1].hour)cost=rate[tRecords[i].hour]*ticks/100.0;
                else{
                    int min1=60-tRecords[i].minute;
                    int min2=tRecords[i+1].minute;
                    int totalHours=(ticks-min1-min2)/60;
                    cost += min1*rate[tRecords[i].hour]/100.0+min2*rate[tRecords[i+1].hour]/100.0;
                    int startHour=tRecords[i].hour+1;
                    for(int j=startHour;j<startHour+totalHours;j++)cost+=60.0*rate[ j%24 ]/100.0;
                }
                totalCost+=cost;
                printf("%.2f\n",cost);
            }
        }
        if(totalCost!=0)printf("Total amount: $%.2f\n",totalCost);
    }

    return 0;
}



你遇到的错误信息如下: ``` 入住失败:com.ruoyi.system.mapper.BillMapper.insert (batch index #1) failed. Cause: java.sql.BatchUpdateException: Duplicate entry '12-1-2025-09-25' for key 'bills.uk_elderly_item_month' ``` --- ### ✅ 回答问 #### ❓ 问原因分析: 这个错误的核心是: > **你在尝试插入一条账单记录时,违反了数据库表 `bills` 上的一个唯一约束(Unique Key)—— `uk_elderly_item_month`** 具体含义: - `Duplicate entry '12-1-2025-09-25'` 表示你要插入的数据组合 `(elderly_id=12, item_id=1, bill_month='2025-09')` 已经存在。 - 唯一键 `uk_elderly_item_month` 的作用是:**防止同一个老人、同一个费用项目、同一个月生成重复账单。** 📌 所以你现在的问是:**试图为“老人12”的“项目1”在“2025年9月”再次生成账单,但系统已经有一条相同的记录了!** --- ### 🔍 结合你的 Java 代码分析 你在 `generateInitialBill(...)` 方法中每次办理入住都会调用: ```java private void generateInitialBill(Long elderlyId) { List<Bill> bills = new ArrayList<>(); Map<String, BigDecimal> feeItems = new HashMap<>(); feeItems.put("床位费", new BigDecimal("3000.00")); feeItems.put("护理费", new BigDecimal("1500.00")); LocalDate now = LocalDate.now(); for (Map.Entry<String, BigDecimal> entry : feeItems.entrySet()) { Bill bill = new Bill(); bill.setElderlyId(elderlyId); bill.setItemName(entry.getKey()); bill.setAmount(entry.getValue()); bill.setPaidAmount(BigDecimal.ZERO); bill.setStatus("unpaid"); bill.setBillMonth(now); // ← 问在此!每月只能生成一次 bill.setCreateTime(LocalDateTime.now()); // 假设你设置了 item_id if ("床位费".equals(entry.getKey())) { bill.setItemId(1L); } else if ("护理费".equals(entry.getKey())) { bill.setItemId(2L); } bills.add(bill); } billService.saveBatch(bills); // ← 这里触发唯一键冲突 } ``` ⚠️ 每次办理入住都执行此逻辑 → 可能多次生成同一月账单 → 冲突! --- ### ✅ 解决方案(推荐四种策略) #### ✅ 方案一:【推荐】插入前先检查是否已存在相同账单 修改 `generateInitialBill` 方法,在插入前查询是否存在: ```java private void generateInitialBill(Long elderlyId) { List<Bill> bills = new ArrayList<>(); Map<String, BigDecimal> feeItems = new HashMap<>(); feeItems.put("床位费", new BigDecimal("3000.00")); feeItems.put("护理费", new BigDecimal("1500.00")); LocalDate now = LocalDate.now(); // 查询当前月份已存在的账单项 List<Bill> existingBills = billService.list(new LambdaQueryWrapper<Bill>() .eq(Bill::getElderlyId, elderlyId) .eq(Bill::getBillMonth, now) .in(Bill::getItemId, Arrays.asList(1L, 2L)) // 床位费、护理费 ID ); Set<Long> existingItemIds = existingBills.stream() .map(Bill::getItemId) .collect(Collectors.toSet()); for (Map.Entry<String, BigDecimal> entry : feeItems.entrySet()) { Long itemId = "床位费".equals(entry.getKey()) ? 1L : "护理费".equals(entry.getKey()) ? 2L : 0L; // ✅ 跳过已存在的账单项 if (existingItemIds.contains(itemId)) { System.out.println("跳过已存在的账单: " + entry.getKey() + " for month " + now); continue; } Bill bill = new Bill(); bill.setElderlyId(elderlyId); bill.setItemId(itemId); bill.setItemName(entry.getKey()); bill.setAmount(entry.getValue()); bill.setPaidAmount(BigDecimal.ZERO); bill.setStatus("unpaid"); bill.setBillMonth(now); bill.setCreateTime(LocalDateTime.now()); bills.add(bill); } if (!bills.isEmpty()) { billService.saveBatch(bills); System.out.println("成功生成 " + bills.size() + " 条新账单"); } else { System.out.println("本月账单已全部存在,无需生成"); } } ``` --- #### ✅ 方案二:使用 `INSERT IGNORE` 或 `ON DUPLICATE KEY UPDATE` 如果你使用的是 MySQL,并希望自动忽略冲突或更新状态,可以自定义 SQL 映射。 在 `BillMapper.java` 中添加: ```java @Insert("<script>" + "INSERT INTO bills (elderly_id, item_id, item_name, amount, paid_amount, status, bill_month, create_time) " + "VALUES " + "<foreach collection='list' item='item' separator=','>" + "(#{item.elderlyId}, #{item.itemId}, #{item.itemName}, #{item.amount}, #{item.paidAmount}, #{item.status}, #{item.billMonth}, #{item.createTime})" + "</foreach> " + "ON DUPLICATE KEY UPDATE status = VALUES(status), update_time = NOW()" + "</script>") void insertWithOnDuplicateKeyUpdate(@Param("list") List<Bill> bills); ``` 然后在 Service 中调用它代替 `saveBatch()`。 > ⚠️ 注意:这需要你掌握 MyBatis 动态 SQL。 --- #### ✅ 方案三:删除旧账单再插入(仅限测试环境!) 不推荐生产使用,但在调试时可用: ```java // 删除该老人当月账单(危险操作!) billService.remove(new LambdaQueryWrapper<Bill>() .eq(Bill::getElderlyId, elderlyId) .eq(Bill::getBillMonth, now) ); // 然后再 insert billService.saveBatch(bills); ``` ⚠️ 风险极高:可能导致财务数据丢失! --- #### ✅ 方案四:业务层控制:只允许首次入住生成账单 你可以通过 `CheckInRecord` 判断是否是第一次入住: ```java boolean isFirstTime = checkInRecordService.count(new LambdaQueryWrapper<CheckInRecord>() .eq(CheckInRecord::getElderlyId, elderlyId) .last("LIMIT 1")) == 0; if (isFirstTime) { generateInitialBill(elderlyId); } else { System.out.println("非首次入住,跳过初始账单生成"); } ``` --- ### ✅ 如何验证唯一索引? 运行以下 SQL 查看约束: ```sql SHOW CREATE TABLE bills; ``` 输出中会看到类似: ```sql CONSTRAINT uk_elderly_item_month UNIQUE KEY (elderly_id, item_id, bill_month) ``` 这就是导致冲突的根源。 --- ### 总结解释: > 你遇到的 `Duplicate entry '12-1-2025-09-25' for key 'uk_elderly_item_month'` 错误,根本原因是:**数据库表 `bills` 上定义了一个唯一索引,确保每个老人、每个费用项目、每个月只能有一条账单记录**。而你在办理入住时未做去重判断,导致重复插入相同账单,从而触发唯一键冲突。解决方案是:**在插入前查询已有账单并跳过重复项,或改用 `ON DUPLICATE KEY UPDATE` 语法处理冲突**。这是典型的“幂等性缺失”问,在自动化账单生成场景中必须防范。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值