1016 Phone Bills

该问题是一个编程任务,要求根据给定的费率结构和电话通话记录,计算并输出客户的电话账单。输入包括24小时的费率和多个电话记录,输出需按客户姓名和时间顺序列出账单详情及总费用。算法涉及时间戳处理、话费计算和数据排序。

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

代码长度限制

16 KB

时间限制

200 ms

内存限制

64 MB

汉化版本

长途电话公司按以下规则向客户收费:

拨打长途电话每分钟要花费一定的费用,具体收费取决于拨打电话的时间。

客户开始拨打长途电话的时间将被记录,客户挂断电话的时间也将被记录。

每个月都要给客户发送一次话费账单,账单中应包含每次通话记录以及相关收费等信息。

给定一组电话记录,你的工作是为客户准备帐单。

输入格式

输入包含两部分:费率结构和电话记录。

费率结构由一行组成,该行包含24个非负整数,分别表示从 00:00-01:00 的收费(分/分钟),从 01:00-02:00 的收费,以此类推…

下一行包含一个正整数 NN。

接下来 NN 行,每行包含一条记录。

每个记录由客户名称(最多 2020 个字符的字符串,不带空格),时间和日期(mm:dd:hh:mm)以及单词 on-line 或 off-line 组成。

所有日期都在同一个月内,每个 on-line 记录都与按时间顺序排列的同一位客户的下一条记录配对,但前提是这条记录是 off-line

所有未与 off-line 记录配对的 on-line 记录以及未与 on-line 记录配对的 off-line 记录都必须忽略。

输入中至少包含一个成功的配对。

同一客户在同一时间不会有两个或以上的电话记录。

使用 2424 小时制记录时间。

输出格式

你需要为每个客户打印电话费。

账单必须按照客户姓名的字母顺序(按ASCII码顺序,大写字母在前,小写字母在后)打印。

对于每个客户,首先以示例显示的格式在一行中打印客户名称和帐单月份。

然后,对于每个通话时间段,在一行中分别打印开始和结束时间和日期(dd:hh:mm),持续时间(以分钟为单位)和通话费用。

通话必须按时间顺序列出。

最后,以示例显示的格式打印该月的总费用。

注意,没有任何有效通话记录的客户直接忽略,不予打印账单。

数据范围

1≤N≤10001≤N≤1000

输入样例:

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

输出样例:

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 <map>
#include <vector>
#include <algorithm>

using namespace std;

const int MINUTE = 31*24*60+10;
int rates[24];
int counts[MINUTE];     // 时间戳以分钟为单位的费率累计

struct record {
    int minutes;
    string format_time;
    string status;

    bool operator< (const record& t) const {
        return minutes < t.minutes;
    }
};

map<string, vector<record>> persons;

int to_minutes(int day, int hour, int minute){
    return (day-1)*60*24 + hour * 60 + minute;
}

int main() {
    for (int i = 0; i < 24 ; i++) cin >> rates[i];
    for (int i = 1; i < MINUTE; i++) counts[i] = counts[i-1] + rates[(i-1)%1440/60];

    int N;
    cin >> N;
    char user[30],format_time[30],status[20];
    int month,day,hour,minute;
    for (int i = 0; i < N; i++) {
        scanf("%s %d:%d:%d:%d %s", user, &month, &day, &hour, &minute, status);
        sprintf(format_time,"%02d:%02d:%02d",day,hour,minute);
        int minutes = to_minutes(day,hour,minute);
        persons[user].push_back({minutes,format_time,status});
    }

    for (auto &person : persons){   // 加&表直接引用,而非复制,提高效率
        auto records = person.second;
        auto user = person.first;
        sort(records.begin(),records.end());
        double total = 0;
        for(int i = 0; i + 1 < records.size(); i++){
            auto a = records[i], b = records[i+1];
            if(a.status == "on-line" && b.status == "off-line"){
                if (!total) printf("%s %02d\n", user.c_str(), month);
                cout << a.format_time << ' ' << b.format_time;
                double cost = counts[b.minutes] - counts[a.minutes];
                printf(" %d $%.2lf\n", b.minutes-a.minutes, cost/100);
                total += cost;
            }
        }
        if (total) printf("Total amount: $%.2lf\n", total/100);
    }
	return 0;
}

 总结

1. 这是一道很臭很长的模拟题,根据题目要求我们需要先梳理清楚数据关系,首先是分时段不同价格的话费表,然后是不同用户的多次通话记录,排列上无序。要求我们根据条件筛选出有效的数据然后进行话费的计算。

2. 计算话费的核心思想,先列出一个从0时间点到某一个时间点(单位为分钟)的话费总和表,然后用户每次通话的话费只需要将两个时间戳对应的话费总和相减即为该段通话的话费。

3. 区分不同用户的通话记录,考虑采用以用户名作为键的Map来记录某个用户的所有通话记录,这里需要用到vector容器来记录每个用户的所有通话记录。每个记录用包含有通话时间戳、格式化时间(方便输出)以及通话状态的结构体记录。为了方便vector排序,在结构体内定义operator重载。

4. 对于scanf,因为string不是c中的原始对象类型,所以无法使用,需要将字符串定义为字符数组形式,才能使用scanf输入。

5. sprintf用于将格式化字符串输出到指定字符数组中。

6. 格式化输入输出的注意。

const handleExport = async () => { try { loading.value = true; // 格式化日期参数 const params = { billType: searchForm.billType, paymentStatus: searchForm.paymentStatus, accountId: searchForm.accountId, startDate: searchForm.dateRange?.[0] ? dayjs(searchForm.dateRange[0]).format("YYYY-MM-DD") : undefined, endDate: searchForm.dateRange?.[1] ? dayjs(searchForm.dateRange[1]).format("YYYY-MM-DD") : undefined, }; console.log("导出参数:", params); const response = await exportBill(params); console.log("响应数据:", response); // 处理Blob数据 const blob = new Blob([response.data], { type: response.headers["content-type"] || "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", }); // 创建下载链接 const url = window.URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.setAttribute( "download", `账单_${new Date().toISOString().slice(0, 10)}.xlsx` ); document.body.appendChild(link); link.click(); // 清理 setTimeout(() => { document.body.removeChild(link); window.URL.revokeObjectURL(url); }, 100); ElMessage.success("导出成功"); } catch (error) { console.error("导出错误详情:", error); // 处理后端返回的JSON错误信息 if ( error.response && error.response.data && error.response.data instanceof Blob ) { const reader = new FileReader(); reader.onload = () => { try { const errMsg = JSON.parse(reader.result).message; ElMessage.error(`导出失败: ${errMsg}`); } catch (e) { ElMessage.error("导出失败: 未知错误"); } }; reader.readAsText(error.response.data); } else { ElMessage.error(`导出失败: ${error.message || "未知错误"}`); } } finally { loading.value = false; } };@GetMapping("/exportBill") public void exportBill( @RequestParam(required = false) Integer billType, @RequestParam(required = false) Integer paymentStatus, @RequestParam(required = false) Long accountId, @RequestParam(required = false) String startDate, @RequestParam(required = false) String endDate, HttpServletResponse response) throws IOException { log.info("导出参数: billType={}, paymentStatus={}, accountId={}, startDate={}, endDate={}", billType, paymentStatus, accountId, startDate, endDate); try { // 1. 构建查询参数 BillExportReqDTO exportDTO = new BillExportReqDTO(); exportDTO.setBillType(billType); exportDTO.setPaymentStatus(paymentStatus); exportDTO.setAccountId(accountId); // 日期转换处理 if (StringUtils.isNotBlank(startDate)) { exportDTO.setStartDate(Date.valueOf(startDate)); } if (StringUtils.isNotBlank(endDate)) { exportDTO.setEndDate(Date.valueOf(endDate)); } // 2. 设置响应头 String fileName = "账单_" + LocalDate.now() + ".xlsx"; response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8")); // 3. 导出Excel billService.exportBill(exportDTO, response.getOutputStream()); } catch (Exception e) { log.error("导出Excel失败", e); response.reset(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(String.valueOf(Result.error("导出失败: " + e.getMessage()))); } } @Override public void exportBill(BillExportReqDTO exportDTO, OutputStream outputStream) { // 1. 查询数据 List<bills> bills = billMapper.selectBillsForExport(exportDTO); if (CollectionUtils.isEmpty(bills)) { throw new RuntimeException("没有可导出的数据"); } // 2. 导出Excel try (ExcelWriter excelWriter = EasyExcel.write(outputStream) .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽 .build()) { WriteSheet writeSheet = EasyExcel.writerSheet("账单数据") .head(BillExcelRespDTO.class) .registerWriteHandler(new HorizontalCellStyleStrategy( getHeaderStyle(), getContentStyle())) // 自定义样式 .build(); // 3. 数据转换并写入Excel excelWriter.write(convertToExcelVO(bills), writeSheet); excelWriter.finish(); // 确保写入完成 } } private List<BillExcelRespDTO> convertToExcelVO(List<bills> bills) { return bills.stream().map(bill -> { BillExcelRespDTO vo = new BillExcelRespDTO(); // 这里进行属性拷贝 BeanUtils.copyProperties(bill, vo); // 特殊字段处理 vo.setPaymentStatus(String.valueOf(bill.getPaymentStatus())); return vo; }).collect(Collectors.toList()); } // 内容单元格样式 private WriteCellStyle getContentStyle() { WriteCellStyle style = new WriteCellStyle(); // 1. 对齐方式 style.setHorizontalAlignment(HorizontalAlignment.CENTER); // 水平居中 style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中 // 2. 边框设置 style.setBorderLeft(BorderStyle.THIN); // 左边框 style.setBorderRight(BorderStyle.THIN); // 右边框 style.setBorderTop(BorderStyle.THIN); // 上边框 style.setBorderBottom(BorderStyle.THIN); // 下边框 style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); // 边框颜色 style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); // 3. 背景色(默认白色,可不设置) style.setFillPatternType(FillPatternType.SOLID_FOREGROUND); style.setFillForegroundColor(IndexedColors.WHITE.getIndex()); // 4. 字体样式 WriteFont font = new WriteFont(); font.setFontName("宋体"); // 字体 font.setFontHeightInPoints((short) 11); // 字号 font.setColor(IndexedColors.BLACK.getIndex()); // 字体颜色 style.setWriteFont(font); // 5. 自动换行(根据需求) style.setWrapped(true); return style; } // 自定义表头样式 private WriteCellStyle getHeaderStyle() { WriteCellStyle style = new WriteCellStyle(); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setHorizontalAlignment(HorizontalAlignment.CENTER); // 其他样式设置... return style; }, <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.bankmanage.mapper.BillMapper"> <select id="selectBillsForExport" resultType="com.example.bankmanage.entity.bills"> SELECT * FROM bills <where> <if test="billType != null"> AND bill_type = #{billType} </if> <if test="paymentStatus != null"> AND payment_status = #{paymentStatus} </if> <if test="accountId != null"> AND account_id = #{accountId} </if> <if test="startDate != null"> AND due_date >= #{startDate} </if> <if test="endDate != null"> AND due_date <![CDATA[<=]]> #{endDate} </if> </where> ORDER BY due_date DESC </select> </mapper> package com.example.bankmanage.dto.resq; import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.format.DateTimeFormat; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.math.BigDecimal; import java.sql.Date; @Data @NoArgsConstructor @AllArgsConstructor @Builder @SuppressWarnings("all") public class BillExcelRespDTO { @ExcelProperty("账单编号") private String billNo; @ExcelProperty("账户ID") private Long accountId; @ExcelProperty("账单类型") private String billType; @ExcelProperty("金额") private BigDecimal amount; @ExcelProperty("支付状态") private String paymentStatus; @ExcelProperty("创建时间") @DateTimeFormat("yyyy-MM-dd HH:mm:ss") private Date createTime; @ExcelProperty("支付时间") @DateTimeFormat("yyyy-MM-dd HH:mm:ss") private Date paymentTime; } 根据以上代码为什么我Excel导出指令不成功,请给我一个修正版
06-06
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值