最近初学c++来练习算法题,将pta 的题目重新用c++写一遍,顺便熟悉c++常用stl库及api
电话账单问题(模拟问题)
// 代码
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<map>
#include<vector>
using namespace std;
const int N = 1010, M = 31 * 1440 + 10;
double cost[M];
struct Records{
int minutes;
string state;
string format_time;
bool operator< (const Records& t) const
{
return minutes < t.minutes;
}
};
map<string, vector<Records>> persons;
int main()
{
int time[24];
for(int i = 0; i < 24; i++)cin >> time[i];
int n;
for(int i = 1; i < M; i++) cost[i] = cost[i - 1] + time[(i - 1) % 1440 / 60] * 0.01; //前缀和
cin >> n;
char name[30], state[30], format_time[30];
int month, day, hour, minute;
for(int i = 0; i < n ; i++)
{
scanf("%s %d:%d:%d:%d %s", name, &month, &day, &hour, &minute, state);
sprintf(format_time, "%02d:%02d:%02d", day, hour, minute);
int minutes = (day - 1) * 1440 + hour * 60 + minute;
persons[name].push_back({minutes, state, format_time});
}
for(auto& person : persons) //通过直接调用实参,能减少创建形参的时间
{
string name = person.first;
auto records = person.second;
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.state == "on-line" && b .state == "off-line")
{
if(!total)printf("%s %02d\n", name.c_str(), month);
cout << a.format_time << ' ' << b.format_time << ' ' << b.minutes - a.minutes << ' ';
double money = cost[b.minutes] - cost[a.minutes];
printf("$%.2lf\n", money);
total += money;
}
}
if(total)
{
printf("Total amount: $%.2lf\n", total);
}
}
return 0;
}
前缀和:适用于连续区间之间的差值问题
const int N = 1010, M = 31 * 1440 + 10;
double cost[M];
for(int i = 1; i < M; i++)
cost[i] = cost[i - 1] + time[(i - 1) % 1440 / 60] * 0.01; //前缀和
// i-1 : 分钟将会向上取整 (6:59 ~ 7 : 00 还是算在6点的价格)
// %1440 : 将分钟限制在一天内
// /60 : 将分钟划分出特定的小时段
// 定义每一分钟的和 (通过前一分钟的和与当前分钟的话费相加实现)
vector(可变长数组,有点类似Java中的ArrayList)
#include<vector> //引入头文件
struct Recrods{
int minutes;
string state;
string format_time;
// 制定构造器自动排序规则
bool opetator< (const Records& t) const
{
return minutes < t.minutes;
}
}
int main()
{
map<string, vector<Records>> persons;
for(auto person: persons )
{
auto records = person.second;
// 通过结构体中的构造器进行自定义排序
sort(records.begin(), records.end());
}
}
scanf 、sprintf
#include<iostream>
#include<cstring>
#include<cstdio>
char name[30], state[30], format_time[30];
int month, day, hour, minute;
scanf("%s %d:%d:%d:%d %s", name, &month, &day, &hour, &minute, state);
// scanf能根据特定的输入导入要求的数据
sprintf(format_time, "%02d:%02d:%02d", day, hour, minute);
// sprintf能将特定的输入导出到元素中