PAT刷题:1016. Phone Bills (25)

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本题有个大坑:如果客户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;
}



import os import time from PySide2.QtWidgets import QApplication, QProgressBar, QTextBrowser, \ QFileDialog from PySide2.QtUiTools import QUiLoader from PySide2 import QtCore from auto_accounting import AutoAccounting class MainWindows: def __init__(self): self.ui = QUiLoader().load('./ui/auto_accounting.ui') self.ele_dir_path = "" self.fuel_dir_path = "" self.ui.import_electric.clicked.connect(self.import_electric_path) self.ui.import_fuel.clicked.connect(self.import_fuel_path) self.ui.start.clicked.connect(self.go_statics) @staticmethod def __tb_display(tb, word: str = '', middle: bool = True, clear: bool = True): if clear: tb.clear() if word: tb.append(word) if middle: tb.setAlignment(QtCore.Qt.AlignCenter) def import_electric_path(self): self.ele_dir_path = QFileDialog.getExistingDirectory(None, "选择充电发票路径", os.getcwd()) self.ele_dir_path = f"{self.ele_dir_path}/" self.__tb_display(tb=self.ui.electric_file_path_display, word=self.ele_dir_path, middle=False) def import_fuel_path(self): self.fuel_dir_path = QFileDialog.getExistingDirectory(None, "选择加油发票路径", os.getcwd()) self.fuel_dir_path = f"{self.fuel_dir_path}/" self.__tb_display(tb=self.ui.fuel_file_path_display, word=self.fuel_dir_path, middle=False) def go_statics(self): self.__tb_display(tb=self.ui.monitor, word="统计中...", middle=False) if not self.ele_dir_path and not self.fuel_dir_path: self.__tb_display(tb=self.ui.monitor, word="请至少添加一个路径!", middle=False) return False A = AutoAccounting(electric_path=self.ele_dir_path, fuel_path=self.fuel_dir_path) files_ck_res = A.bill_abstract() if files_ck_res: self.__tb_display(tb=self.ui.monitor, word="", middle=False) for file_ck_res in files_ck_res: words = file_ck_res[1]+file_ck_res[2] self.__tb_display(tb=self.ui.monitor, word=words, middle=False, clear=False) elif A.wrong_bills: print(A.wrong_bills) self.__tb_display(tb=self.ui.monitor, word="", middle=False) for wrong_bill in A.wrong_bills: self.__tb_display(tb=self.ui.monitor, word=wrong_bill, middle=False, clear=False) else: self.__tb_display(tb=self.ui.monitor, word="已完成发票统计!", middle=False) app = QApplication([]) stats = MainWindows() stats.ui.show() app.exec_() 为什么”统计中...“无法显示在monitor文本框内
最新发布
07-23
<think>我们正在解决PySide2中QTextBrowser的append方法无法实时显示内容的问。根据引用[4],我们可以使用QTextCursor来移动光标并插入文本,这样可以避免实时更新问。同时,引用[3]展示了如何使用QTextBrowser并连接按钮点击事件来追加文本,但可能同样遇到更新不及时的问。 解决方案思路: 1. 使用QTextCursor操作,在文本末尾插入新内容。 2. 确保在插入文本后,立即更新视图。 然而,根据引用[4]提供的方法,我们可以这样实现: - 获取QTextBrowser的文本光标(QTextCursor) - 将光标移动到文档末尾 - 使用光标的insertText方法插入文本 但注意:在PySide2中,我们也可以使用append方法,但用户反映append方法不能实时更新。因此,我们可以尝试使用QTextCursor的方法,并在插入文本后调用`repaint()`或`update()`来强制更新。 然而,更常见的原因是界面线程被长时间操作阻塞,导致界面无法更新。因此,如果我们在一个循环中多次追加文本,那么每次追加后都应该让事件循环有机会处理界面更新。 所以,有两种可能: 1. 使用QTextCursor并确保在每次插入后处理事件(使用QApplication.processEvents())。 2. 或者,使用append方法,并在每次追加后调用QApplication.processEvents()。 但是,引用[4]提供的方法(使用QTextCursor)在C++中有效,在Python中同样可以尝试。 我们尝试编写代码示例: 方法一:使用append并处理事件 ```python self.text_browser.append("新的文本") QApplication.processEvents() # 强制处理事件,更新界面 ``` 方法二:使用QTextCursor ```python cursor = self.text_browser.textCursor() cursor.movePosition(QtGui.QTextCursor.End) cursor.insertText("新的文本\n") # 插入文本并换行 self.text_browser.setTextCursor(cursor) # 将光标设置回去,以便显示光标位置 self.text_browser.ensureCursorVisible() # 确保光标可见 # 或者使用以下方式更新 self.text_browser.repaint() # 或者调用processEvents QApplication.processEvents() ``` 但是,根据引用[3]的示例,他们使用了append方法,并且没有提到更新问。因此,我们需要考虑用户的具体使用场景,比如是否在长时间循环中追加文本。 因此,建议用户: 1. 如果在循环中追加,每次追加后调用QApplication.processEvents()。 2. 或者使用QTextCursor的方式,并同样在每次插入后处理事件。 下面我们提供一个完整的示例,展示如何实时更新QTextBrowser的内容。 示例代码: ```python import sys import time from PySide2.QtWidgets import QApplication, QMainWindow, QTextBrowser, QPushButton, QVBoxLayout, QWidget class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle('QTextBrowser实时更新示例') self.central_widget = QWidget() self.setCentralWidget(self.central_widget) layout = QVBoxLayout(self.central_widget) self.text_browser = QTextBrowser() self.button_start = QPushButton('开始追加文本') self.button_start.clicked.connect(self.start_appending) layout.addWidget(self.text_browser) layout.addWidget(self.button_start) def start_appending(self): # 模拟一个长时间的操作,每次追加文本并更新 for i in range(10): # 使用方法一:append并处理事件 self.text_browser.append(f"这是第 {i+1} 行文本") # 强制处理事件,更新界面 QApplication.processEvents() # 模拟耗时操作 time.sleep(1) if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_()) ``` 在这个示例中,我们创建了一个窗口,包含一个QTextBrowser和一个按钮。点击按钮后,会开始循环10次,每次追加一行文本并暂停1秒。在每次追加后调用`QApplication.processEvents()`,这样界面就会实时更新。 注意:在耗时操作中,如果使用time.sleep会阻塞主线程,导致界面卡住。更好的做法是使用多线程或QTimer来模拟耗时操作,但这里为了简单演示更新问,我们直接在主线程中使用了sleep,并配合processEvents来更新界面。 因此,用户的问可以通过在每次append后调用`QApplication.processEvents()`来解决。 如果用户不想使用processEvents,也可以考虑使用QTimer来分次追加,这样就不会阻塞事件循环。 另外,引用[4]中提到的QTextCursor方法,我们也可以给出一个示例: ```python def append_text_with_cursor(self, text): cursor = self.text_browser.textCursor() cursor.movePosition(QtGui.QTextCursor.End) cursor.insertText(text + '\n') self.text_browser.setTextCursor(cursor) self.text_browser.ensureCursorVisible() # 不需要repaint,因为插入文本会触发更新,但如果更新被阻塞,还是需要processEvents # 所以如果是在循环中,同样需要调用processEvents QApplication.processEvents() ``` 但是,在循环中,无论使用append还是QTextCursor,都需要processEvents来及时更新。 总结:解决QTextBrowser无法实时更新的关键在于,在追加文本后让事件循环有机会处理界面重绘事件。可以通过调用`QApplication.processEvents()`来实现。 注意:频繁调用processEvents可能会带来其他事件的处理,比如用户点击按钮等,因此需要确保在长时间操作中,用户不能重复触发操作(例如禁用按钮)。 因此,我们更推荐使用异步的方式,比如使用QTimer来分次更新,或者使用多线程将耗时任务放在后台,然后通过信号槽来更新界面。 但针对用户当前的问(append方法无法实时更新),最简单的解决方案就是在每次append后调用`QApplication.processEvents()`。 相关问: 1. 为什么PySide2中QTextBrowser的append方法不会实时更新? 2. 在PySide2中,除了使用processEvents,还有哪些方法可以实现界面实时更新? 3. 如何避免在长时间循环中调用processEvents带来的副作用?</think>### 解决 PySide2 中 QTextBrowser 无法实时显示内容的问 在 PySide2 中,`QTextBrowser.append()` 方法无法实时更新显示内容通常是因为 **界面事件循环被阻塞** 或 **未正确新界面**。以下是解决方案和代码示例: #### 核心解决方法 1. **强制新界面** 在每次调用 `append()` 后,使用 `QApplication.processEvents()` 强制处理事件队列: ```python from PySide2.QtWidgets import QApplication def append_text(self, text): self.text_browser.append(text) QApplication.processEvents() # 强制立即处理事件 ``` 2. **使用 QTextCursor 直接插入文本**(推荐) 参考引用[4]的方法,避免 `append()` 的新问: ```python def append_text(self, text): cursor = self.text_browser.textCursor() cursor.movePosition(cursor.End) # 移动到文档末尾 cursor.insertText(text + "\n") # 插入文本并换行 self.text_browser.setTextCursor(cursor) # 更新光标位置 self.text_browser.ensureCursorVisible() # 确保光标可见 ``` #### 完整示例代码 ```python from PySide2.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QTextBrowser from PySide2.QtGui import QTextCursor class TextBrowserDemo(QWidget): def __init__(self): super().__init__() self.setWindowTitle("QTextBrowser 实时更新示例") self.setGeometry(300, 300, 400, 300) # 创建控件 self.text_browser = QTextBrowser() self.button = QPushButton("添加文本") self.button.clicked.connect(self.add_text) # 布局 layout = QVBoxLayout() layout.addWidget(self.text_browser) layout.addWidget(self.button) self.setLayout(layout) def add_text(self): # 方法1:使用 processEvents(简单但可能影响性能) # self.text_browser.append("新内容 - 方法1") # QApplication.processEvents() # 方法2:使用 QTextCursor(推荐) cursor = self.text_browser.textCursor() cursor.movePosition(QTextCursor.End) cursor.insertText("实时更新的新内容 - 方法2\n") self.text_browser.setTextCursor(cursor) self.text_browser.ensureCursorVisible() if __name__ == "__main__": app = QApplication([]) window = TextBrowserDemo() window.show() app.exec_() ``` #### 问原因分析 1. **事件循环阻塞** 当主线程执行耗时操作(如循环、网络请求)时,界面事件循环被阻塞,导致更新无法及时渲染。 2. **append() 的内部机制** `append()` 会添加新段落,但在某些情况下需要手动触发新(尤其在频繁更新时)。 3. **线程安全问** 如果在非主线程更新界面,必须使用信号槽机制跨线程通信。 #### 高级场景优化 - **频繁更新场景**:使用 `QTextCursor` 直接操作文档,避免频繁创建段落 - **多线程场景**:通过信号槽机制跨线程更新 ```python class Worker(QObject): update_signal = Signal(str) def run(self): self.update_signal.emit("从线程更新的内容") # 主窗口中连接信号 worker = Worker() worker.update_signal.connect(self.text_browser.append) ``` - **大文本处理**:定期调用 `ensureCursorVisible()` 保持滚动条位置
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值