【题意】
给出了一些用户的通话时间记录,输出月账单
【思路】
先将输入的记录存在vector中,按照姓名字典序、时间顺序排序,然后再从前往后匹配on-line和off-line
【注意点/易错点】
1. 对于没有产生任何消费的用户,账单里一点信息也不能输出(有点坑,明明有一句“
For each test case, you must print a phone bill for each customer”,简直了= =);
2. 计算话费时要考虑开始和结束时间在同一小时的
临界情况,如 01:01:21:58-01:01:21:59 ,原本我采用的是头尾+中间的方法,在这种情况下就会出问题了。(如果费用都从00:00算起,然后再相减就可以避免这种容易犯的错误,下次碰上类似的计算问题可以考虑这种相减的思路)
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cstdio>
using namespace std;
int rate[24];
typedef struct{
string name;
string t;
int tag;// 0 for on-line, 1 for off-line
int d;
int h;
int m;
}record;
bool earlier(record a, record b){
if (a.d<b.d || (a.d==b.d && a.h<b.h) || (a.d==b.d && a.h==b.h && a.m<b.m))
{
return true;
}
else
{
return false;
}
}
bool cmp(record a, record b){
if (a.name<b.name)
{
return 1;
}
else if (a.name==b.name && earlier(a,b))
{
return 1;
}
else
return 0;
}
float cal(record r1, record r2){
float sum=0.0;
float daycost=0.0;
for(int i=0; i<24; i++){
daycost += rate[i]*60;
}
sum += (r2.d-r1.d)*daycost;
if(r1.h<=r2.h){
sum = sum+(60-r1.m)*rate[r1.h]+(r2.m)*rate[r2.h];
for(int i=r1.h+1; i<r2.h; i++){
sum += rate[i]*60;
}
}
else{
sum = sum-(60-r2.m)*rate[r2.h]-(r1.m)*rate[r1.h];
for(int i=r2.h+1; i<r1.h; i++){
sum -= rate[i]*60;
}
}
sum /= 100;
return sum;
}
int main(int argc, char const *argv[])
{
int n;
vector<record> records;
record tmp;
string month;
for (int i = 0; i < 24; ++i)
{
cin >> rate[i];
}
cin >> n;
for (int i = 0; i < n; ++i)
{
string name;
string t;
string tag;
cin >> name >> t >> tag;
tmp.name = name;
tmp.t = t;
if(tag == "on-line")
tmp.tag = 0;
else
tmp.tag = 1;
tmp.d = (tmp.t[3]-'0')*10+tmp.t[4]-'0';
tmp.h = (tmp.t[6]-'0')*10+tmp.t[7]-'0';
tmp.m = (tmp.t[9]-'0')*10+tmp.t[10]-'0';
records.push_back(tmp);
}
sort(records.begin(), records.end(), cmp);
month.assign((*records.begin()).t,0,2);
string currentName="";
int tag;
float total;
bool first;
for (vector<record>::iterator it = records.begin(); it != records.end();)
{
string currentTime;
record tmpRecord;
if ((*it).name!=currentName)
{
tag = 0;
total = 0.0;
first = true;
currentName = (*it).name;
//cout << (*it).name << " ";
//cout << ((*it).t)[0] << ((*it).t)[1] << endl;
while((*it).tag!=tag && (*it).name==currentName){
it++;
}
}
while(it != records.end() && (*it).name==currentName){
if((*it).tag==tag){
if(tag==0){
tmpRecord = *it;
tag = 1;
}
else{
if(first){
cout << (*it).name << " " << month << endl;
first = false;
}
printf("%02d:%02d:%02d ", tmpRecord.d, tmpRecord.h, tmpRecord.m);
printf("%02d:%02d:%02d ", (*it).d, (*it).h, (*it).m);
cout << (((*it).d-tmpRecord.d)*24+(*it).h-tmpRecord.h)*60+(*it).m-tmpRecord.m << " ";
float cost = cal(tmpRecord, *it);
total += cost;
printf("$%.2f\n", cost);
tag = 0;
}
}
else if(tag==1){
tmpRecord = *it;
}
it++;
}
if(!first)
printf("Total amount: $%.2f\n", total);
}
system("pause");
return 0;
}