1016 Phone Bills

文章介绍了如何根据通话记录计算每月顾客的电话费用,涉及处理跨天情况的算法,以及从复杂问题中简化思路的方法。通过比较不同解题策略,强调了灵活运用线程和高效算法的重要性。

1016 Phone Bills

题目大意

题目信息很多,需要逐个分析才行,干扰也比较多,大意就是根据给出的顾客的通话记录,打印出该月每个顾客的费用

算法思想

  • 一开始真的没写出来,后面去看了柳神的代码,五体投地,弄懂了之后,自己又重新看着题目写了一遍。
  • 坑点大概就是跨天,不过可以从0:0:0:0开始计算每个时间的,然后相减,就可以避免掉。
  • 注释写的很详细,可以看注释
  • 第一次写这么复杂的题目,本以为能够慢慢写出来,结果发现有可能跨天,直接放弃了,后面看了柳神的代码,发现和我的想法最大的不同在于,柳神可以非常灵活的利用各种线程,而且算法思想仿佛可以由繁化简,操控整个程序,各个部分衔接非常的好,而我的就好像是在拼接在一起,任重而道远。
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
using namespace std;
struct node {
	string id;
	int status, time, month, day, hour, minute;
};
bool cmp(node a, node b)
{
	if (a.id != b.id)
		return a.id < b.id;//id小的排前面,题目要求
	else
		return a.time < b.time;//id相等时,时间小的排前面
}
double monkey(node s,vector<int>charge)//从0:0:0开始到s时间,所用费用
{
	double mon = s.day * 60 * charge[24] + charge[s.hour] * s.minute;//先计算天数花费的钱,以及末尾分钟花费的钱
	for (int i = 0; i < s.hour; i++)//计算剩余小时花费的钱
	{
		mon += charge[i] * 60;
	}
	return mon / 100;//转成美元
}
int main()
{
	vector<int>charge(25);//记录24小时价格
	for (int i = 0; i < 24; i++)
	{
		int t;
		cin >> t;
		charge[i] = t;
		charge[24] += charge[i];//记录一天花费的价格
	}
	int n;
	cin >> n;
	vector<node>s(n);//读取输入信息
	for (int i = 0; i < n; i++)
	{
		string ti, sta;
		cin >> s[i].id >> ti >> sta;
		sscanf(ti.c_str(), "%d:%d:%d:%d", &s[i].month, &s[i].day, &s[i].hour, &s[i].minute);//读取时间
		s[i].time = s[i].day * 24 * 60 + s[i].hour * 60 + s[i].minute;//time变量用于排序
		if (sta == "on-line")//读取状态
			s[i].status = 1;
		else
			s[i].status = 0;
	}
	sort(s.begin(), s.end(), cmp);//排序
	map<string, vector<node>>bill;
	for (int i = 1; i < n; i++)
	{
		if (s[i].id == s[i - 1].id && s[i - 1].status == 1 && s[i].status == 0)//前后两个id相等,一前一后刚好是对应的on和off时,配对成功
		{
			bill[s[i].id].push_back(s[i - 1]);//一前一后对应一个id
			bill[s[i].id].push_back(s[i]);
		}
	}
	for (auto it : bill)//遍历账单
	{
		vector<node>now = it.second;
		printf("%s %02d\n",it.first.c_str(), now[0].month);
		double total = 0;
		for (int i = 1; i < now.size(); i += 2)//账单下的通话记录,两个一组
		{
			double money = monkey(now[i], charge) - monkey(now[i - 1], charge);//计算花费
			printf("%02d:%02d:%02d %02d:%02d:%02d %d $%.2f\n", now[i - 1].day, now[i - 1].hour, now[i - 1].minute, now[i].day, now[i].hour, now[i].minute, now[i].time - now[i - 1].time, money);
			total += money;
		}
		printf("Total amount: $%.2f\n", total);
	}
	return 0;
}
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
### 修正后的Excel导出功能实现 #### 后端逻辑修正 在后端代码中,`SysUserController.java` 的 `exportExcelUser` 方法可能存在以下问题:文件生成失败、文件下载失败或请求参数不完整。以下是修正后的代码: ```java @PostMapping(value = "/exportExcelUser") public void exportExcelUser(@RequestBody PageRequest pageRequest, HttpServletResponse response) { try { // 确保传入的PageRequest对象包含所有必要参数 if (pageRequest == null || pageRequest.getConditions() == null) { throw new IllegalArgumentException("请求参数为空"); } // 调用服务层生成Excel文件 File file = sysUserService.createUserExcelFile(pageRequest); // 检查文件是否成功生成 if (file == null || !file.exists()) { throw new IOException("Excel文件生成失败"); } // 设置响应头,确保浏览器能够正确下载文件 response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8")); // 下载文件 FileUtils.downloadFile(response, file, file.getName()); // 删除临时文件以节省服务器空间 if (!file.delete()) { logger.warn("临时文件删除失败:" + file.getAbsolutePath()); } } catch (Exception e) { // 捕获异常并返回错误信息 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentType("text/plain;charset=UTF-8"); try { response.getWriter().write("导出失败:" + e.getMessage()); } catch (IOException ex) { logger.error("导出失败时无法写入响应内容", ex); } throw new RuntimeException("Excel导出失败", e); } } ``` 上述代码增加了对 `PageRequest` 参数的校验[^1],并确保文件生成失败时抛出异常。同时,通过设置响应头和删除临时文件的方式优化了文件下载流程。 #### MyBatis查询修正 假设 `sysUserService.createUserExcelFile(PageRequest pageRequest)` 方法依赖于 MyBatis 查询用户数据。如果查询结果为空或映射错误,可能导致 Excel 文件生成失败。以下是修正后的 SQL 和 Mapper 示例: **Mapper XML 文件** ```xml <select id="selectUsersForExport" resultType="com.example.domain.User"> SELECT id, username, email, phone, created_at FROM users <where> <if test="conditions.username != null and conditions.username != ''"> AND username LIKE CONCAT('%', #{conditions.username}, '%') </if> <if test="conditions.email != null and conditions.email != ''"> AND email = #{conditions.email} </if> </where> </select> ``` **MyBatis Mapper 接口** ```java public interface SysUserMapper { List<User> selectUsersForExport(@Param("conditions") Map<String, Object> conditions); } ``` 确保 `ResultMap` 映射正确[^4],并且查询条件与 `PageRequest` 对象中的字段一致。 #### 前端调用修正 前端需要通过 Axios 或 Fetch API 调用后端接口,并处理文件下载。以下是修正后的 Vue.js 前端代码示例: ```javascript methods: { exportExcel() { const params = { conditions: { username: this.searchForm.username, email: this.searchForm.email } }; axios.post('/api/sysUser/exportExcelUser', params, { responseType: 'blob', // 确保响应类型为二进制流 headers: { 'Content-Type': 'application/json' } }).then(response => { const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', '用户列表.xlsx'); // 设置下载文件名 document.body.appendChild(link); link.click(); }).catch(error => { console.error("导出失败:" + error.message); alert("导出失败,请检查日志!"); }); } } ``` 上述代码通过设置 `responseType: 'blob'` 来处理二进制文件流[^2],并动态创建下载链接完成文件保存。 --- ####
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值