杰克船长挖掘到一个宝藏,里面有各种各样的财宝,每种财宝一堆,杰克船长打算每次将两堆财宝合并,直到将这些财宝合并为一堆,显然,经过n-1次合并之后,财宝会成为1堆,假定消耗的体力为两堆财宝的重量之和,为了将这批宝藏搬运到船上,杰克船长必须保证合并时花费的体力最少,你的任务是设计合并方案,计算出最小的体力消耗值。
输入:第一行一个整数N表示有N组测试数据,
接下来的N组测试数据,第一行整数M表示有M种财宝,下一行包括M个整数,表示每种财宝的重量。
输出:消耗的最小体力值
2
3
5 1 7
6
5 8 4 11 9 13
其执行结果为:
19
126
#include
#include
#include
using namespace std;
int main() {
// 输入测试次数
int test_times;
cin >> test_times;
// 用vector来存储数据
vector<int>* list = new vector<int>[test_times];
for (int i = 0; i < test_times; i++) {
// 输入类别
int classification;
cin >> classification;
// 输入每个类别的重量
for (int j = 0; j < classification; j++) {
int weight;
cin >> weight;
list[i].push_back(weight);
}
// 进行排序
sort(list[i].begin(), list[i].end());
}
for (int i = 0; i < test_times; i++) {
int size = list[i].size();
// 输出结果
int result = 0;
if (size > 1) {
while (size > 1) {
int w = list[i][0] + list[i][1];
result += w;
list[i].erase(list[i].begin(), list[i].begin() + 2);
list[i].push_back(w);
sort(list[i].begin(), list[i].end());
size--;
}
cout << result << endl;
}
else {
cout << result;
}
}
return EXIT_SUCCESS;
}
2
3
5 1 7
6
5 8 4 11 9 13
19
126
D:\Private\Files\C++\高级语言程序设计2-2\第十章作业\Project1\Debug\Project1.exe (进程 37360)已退出,代码为 0。
按任意键关闭此窗口. . .
验证可得程序执行正确。
按字典序统计下面这段文字中单词出现的次数
It was the best of times, and it was the worst of times. It was the age of wisdom, and it was the age of foolishness. It was the epoch of belief, and it was the epoch of incredulity. It was the season of light, and it was the season of darkness. It was the spring of hope, and it was the winter of despair. We had everything before us, and we had nothing before us. We were all going direct to Heaven, and we were all going direct the other way. In short, the period was so far like the present period. That some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.
#include
#include
#include
#include
using namespace std;
int main() {
// 利用字典类型map存储key和value
map<string, int> dict;
string input;
// 输入文字段
getline(cin, input, '\n');
string word = "";
// 对文字段进行分词
for (int index = 0; index < input.size(); index++) {
if (input[index] == ',' || input[index] == ' ' || input[index] == '.') {
if (word.size() > 0) {
// 每出现一次,次数进行累加
++dict[word];
word = "";
}
}
else {
word = word + input[index];
}
}
// 统计出现的单词和次数
cout << endl << " Dictionary Show " << endl;
for (auto i = dict.begin(); i != dict.end(); i++) {
cout << "key : " << std::left << setw(12) << i->first;
cout << " value : " << i->second << endl;
}
return EXIT_SUCCESS;
}
验证结果如下:
It was the best of times, and it was the worst of times. It was the age of wisdom, and it was the age of foolishness. It was the epoch of belief, and it was the epoch of incredulity. It was the season of light, and it was the season of darkness. It was the spring of hope, and it was the winter of despair. We had everything before us, and we had nothing before us. We were all going direct to Heaven, and we were all going direct the other way. In short, the period was so far like the present period. That some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.
Dictionary Show
key : Heaven value : 1
key : In value : 1
key : It value : 5
key : That value : 1
key : We value : 2
key : age value : 2
key : all value : 2
key : and value : 7
key : authorities value : 1
key : before value : 2
key : being value : 1
key : belief value : 1
key : best value : 1
key : comparison value : 1
key : darkness value : 1
key : degree value : 1
key : despair value : 1
key : direct value : 2
key : epoch value : 2
key : everything value : 1
key : evil value : 1
key : far value : 1
key : foolishness value : 1
key : for value : 2
key : going value : 2
key : good value : 1
key : had value : 2
key : hope value : 1
key : in value : 1
key : incredulity value : 1
key : insisted value : 1
key : it value : 5
key : its value : 2
key : light value : 1
key : like value : 1
key : noisiest value : 1
key : nothing value : 1
key : of value : 12
key : on value : 1
key : only value : 1
key : or value : 1
key : other value : 1
key : period value : 2
key : present value : 1
key : received value : 1
key : season value : 2
key : short value : 1
key : so value : 1
key : some value : 1
key : spring value : 1
key : superlative value : 1
key : the value : 14
key : times value : 2
key : to value : 1
key : us value : 2
key : was value : 11
key : way value : 1
key : we value : 2
key : were value : 2
key : winter value : 1
key : wisdom value : 1
key : worst value : 1
D:\Private\Files\C++\高级语言程序设计2-2\第十章作业\Project2\Debug\Project2.exe (进程 41380)已退出,代码为 0。
按任意键关闭此窗口. . .
因此,程序执行正确。
编写一个程序,统计每个英文诗词中的诗歌行数和单词个数。
要求:
1、输入使用Poems.txt文件,链接:https://pan.baidu.com/s/14USpQ_VdoFWaNEgxkRuILQ 提取码:st48
2、输出需要格式化输出,每首诗输出一行,每行格式为:T:诗的名称 + P:作者名称 + L:行数 + W:单词数。其中所有的T:P:L:W:都应该上下对齐,标题和诗人左对齐,数字为宽度为5字符的右对齐。参考下图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PJ5VI31j-1603458897834)(C:\Users\c\AppData\Roaming\Typora\typora-user-images\image-20200529195456629.png)]
3、诗中的缩写,如I’m, I’ll 等,理解成用’分隔的两个单词。
#include
#include
#include
#include
using namespace std;
// 统计字数函数
int GetWords(string row) {
int size = row.size();
int num = 1;
for (int index = 0; index < size; index++) {
if (row[index] == ' ' || row[index] == '\'')
num++;
if (row[index] == '-')
num--;
}
return num;
}
int main() {
// 读取每行的数据存储在str内
string str;
int size = 0;
// 读取文件
ifstream infile("Poems.txt");
// 循环读取文件的内容
while (getline(infile, str)) {
size = str.size();
// 标题
string title = str.substr(7, size - 1);
cout << "T: " << std::left << setw(28) << title;
getline(infile, str);
size = str.size();
// 作者
string author = str.substr(6, size - 1);
cout << "P: " << std::left << setw(28) << author;
getline(infile, str);
getline(infile, str);
// 字数和行数
int num = 0, row = 0;
while (str.size() != 0) {
row++;
num += GetWords(str);
getline(infile, str);
}
cout << "L:" << std::right << setw(5) << row;
cout << setw(5) << "W:" << std::right << setw(5) << num << endl;
}
// 关闭文件
infile.close();
return EXIT_SUCCESS;
}
结果如下:
T: My Life Has Been the Poem P: Henry David Thoreau L: 2 W: 19
T: I'm Nobody! Who Are You? P: Emily Dickinson L: 8 W: 47
T: Dreams P: Robert Herrick L: 3 W: 19
T: No Man Is An Island P: John Donn L: 13 W: 94
D:\Private\Files\C++\高级语言程序设计2-2\第十章作业\Project3\Debug\Project3.exe (进程 42620)已退出,代码为 0。
按任意键关闭此窗口. . .
因此,程序执行正确。
将练习题1中,自己写的代码文件作为输入文件,为源代码中每行开头添加一个行号和冒号,并在终端打印输出。
要求:
#include
#include
#include
#include
using namespace std;
int main() {
// 打开文件
ifstream infile("input.txt");
int row = 0;
string content;
while (getline(infile, content)) {
row++;
// 输出行数
cout << std::right << setw(3) << setfill('0') << row << ":";
// 输出每行的内容
cout << content << endl;
}
// 关闭文件
infile.close();
return EXIT_SUCCESS;
}
截图如下:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kwxZbMzk-1603458897840)(C:\Users\c\AppData\Roaming\Typora\typora-user-images\image-20200529223454218.png)]
输出结果如下:
001:#include
002:#include
003:#include
004:#include
005:
006:using namespace std;
007:
008:// 统计字数函数
009:int GetWords(string row) {
010: int size = row.size();
011: int num = 1;
012: for (int index = 0; index < size; index++) {
013: if (row[index] == ' ' || row[index] == '\'')
014: num++;
015: if (row[index] == '-')
016: num--;
017: }
018: return num;
019:}
020:
021:int main() {
022: // 读取每行的数据存储在str内
023: string str;
024: int size = 0;
025: // 读取文件
026: ifstream infile("Poems.txt");
027:
028: // 循环读取文件的内容
029: while (getline(infile, str)) {
030: size = str.size();
031: // 标题
032: string title = str.substr(7, size - 1);
033: cout << "T: " << std::left << setw(28) << title;
034:
035: getline(infile, str);
036: size = str.size();
037: // 作者
038: string author = str.substr(6, size - 1);
039: cout << "P: " << std::left << setw(28) << author;
040:
041: getline(infile, str);
042: getline(infile, str);
043:
044: // 字数和行数
045: int num = 0, row = 0;
046: while (str.size() != 0) {
047: row++;
048: num += GetWords(str);
049: getline(infile, str);
050: }
051: cout << "L:" << std::right << setw(5) << row;
052: cout << setw(5) << "W:" << std::right << setw(5) << num << endl;
053: }
054: // 关闭文件
055: infile.close();
056: return EXIT_SUCCESS;
057:}
D:\Private\Files\C++\高级语言程序设计2-2\第十章作业\Project4\Debug\Project4.exe (进程 40772)已退出,代码为 0。
按任意键关闭此窗口. . .
因此,程序执行正确。
练习题1中的文件夹中的另一个文件 Students.txt里面存放的是由excel另存为txt的文本文件,excel内容如图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-59jX5bCC-1603458897844)(C:\Users\c\AppData\Roaming\Typora\typora-user-images\image-20200529224930378.png)]
请是用输入输出流章节所学知识,将数据从txt文件中读出,完成以下要求后输出到StandardStudent.txt文件中。要求如下:
#include
#include
#include
#include
using namespace std;
int main() {
// 打开文件
ifstream file1("Students.txt");
ofstream file2("StandardStudent.txt");
string content;
getline(file1, content);
file2 << std::left << setw(5) << "ID" << setw(10) << "Name";
file2 << std::right << setw(10) << "English" << setw(10) << "Math" << setw(10) << "Computer";
file2 << std::right << setw(10) << "Average" << setw(10) << "Tuition" << endl;
while (file1 >> content) {
// 对信息进行格式化输出
string name;
int num1, num2, num3;
double average, tuition;
file1 >> name >> num1 >> num2 >> num3 >> average >> tuition;
average = (num1 + num2 + num3) / 3.0;
file2 << std::left << setw(5) << content << setw(10) << name
<< std::right << setw(10) << num1 << setw(10) << num2 << setw(10) << num3;
file2.precision(2);
file2 << setw(10) << std::fixed << average;
file2 << setw(10) << std::scientific << tuition << endl;
}
// 关闭文件
file1.close();
file2.close();
return EXIT_SUCCESS;
}
截图效果如下:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GnGIK1T2-1603458897845)(C:\Users\c\AppData\Roaming\Typora\typora-user-images\image-20200529233857573.png)]
由实验结果可知:程序执行正确。
将练习题1中使用的Poems.txt中的每个英文诗歌提取出来,并单独存到一个文本文件中,一首诗对应一个文件。
要求
#include
#include
#include
#include
#include
using namespace std;
int main() {
// 读取每行的数据存储在str内
string str;
int size = 0;
// 读取文件
ifstream infile("Poems.txt");
// 循环读取文件的内容
while (getline(infile, str)) {
size = str.size();
// 标题
string title = str.substr(7, size - 1);
getline(infile, str);
size = str.size();
// 作者
string author = str.substr(6, size - 1);
// 文件名
string name = title + "__" + author + ".txt";
// 替换出现的标点符号
replace(name.begin(), name.end(), '!', ' ');
replace(name.begin(), name.end(), '?', ' ');
ofstream outfile(name);
cout << name << endl;
getline(infile, str);
getline(infile, str);
// 输入内容
while (str.size() != 0) {
outfile << str << endl;
getline(infile, str);
}
// 关闭文件
outfile.close();
}
// 关闭文件
infile.close();
return EXIT_SUCCESS;
}
截图效果如下:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NgS6F9I4-1603458897846)(C:\Users\c\AppData\Roaming\Typora\typora-user-images\image-20200530001447394.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iP44iLcb-1603458897847)(C:\Users\c\AppData\Roaming\Typora\typora-user-images\image-20200530115041672.png)]
由结果得,程序执行正确。
编写一个程序,将5种商品的商品号、商品名、单价和数量写入二进制文件f.bin中,然后将该文件中的数据读到数组中,并将其输出到屏幕上。
构造商品如下:
id | name | number | price |
---|---|---|---|
001 | 可乐 | 81 | 12.22 |
002 | 电池 | 20 | 99.78 |
003 | 纸巾 | 34 | 78 |
004 | 面包 | 12 | 10.07 |
005 | 烤鸡 | 25 | 16.35 |
构造struct来存储商品信息。
利用write函数将信息写入二进制文件内。
利用read函数对二进制文件进行读取。
保存在数组内。
将结果展示。
#include
#include
#include
#include
using namespace std;
// 商品信息
struct commodity{
string id;
string name;
double price;
int num;
commodity(string id_, string name_, double price_, int num_) :
id(id_), name(name_), price(price_), num(num_) {}
commodity() {}
};
// 写入到二进制文件内
void WriteFile(string filename) {
commodity a("001", "可乐", 12.22, 81);
commodity b("002", "电池", 99.78, 20);
commodity c("003", "纸巾", 21.57, 34);
commodity d("004", "面包", 10.07, 12);
commodity e("005", "烤鸡", 16.35, 25);
ofstream file(filename, ios::binary);
file.write((char*)(&a), sizeof(a));
file.write((char*)(&b), sizeof(a));
file.write((char*)(&c), sizeof(a));
file.write((char*)(&d), sizeof(a));
file.write((char*)(&e), sizeof(a));
file.close();
}
// 从二进制文件内写出信息
void ReadFile(string filename) {
ifstream file(filename, ios::binary);
// 数组存储信息
commodity s[5];
// 循环导入信息
for (int index = 0; index < 5; index++) {
file.read((char*)(&s[index]), sizeof(s[index]));
}
file.close();
cout << std::left << setw(8) << "ID" << setw(8) << "Name" << setw(8) << "Num" << setw(8) << "Price" << endl;
// 循环展示信息
for (int index = 0; index < 5; index++) {
cout << setw(8) << s[index].id << setw(8) << s[index].name << setw(8) <<
s[index].num << setw(8) << s[index].price << endl;
}
}
int main() {
// 二进制文件文件路径
string path = "bf.bin";
//WriteFile(path);
ReadFile(path);
return EXIT_SUCCESS;
}
运行结果如下:
ID Name Num Price
001 可乐 81 12.22
002 电池 20 99.78
003 纸巾 34 21.57
004 面包 12 10.07
005 烤鸡 25 16.35
请按任意键继续. . .
因此,程序执行正确。
编写一个程序从文件f.bin(第1题已建立的文件)中读出任意一种商品的数据并输出到屏幕上。比如输入整数2,则输出第二种商品的信息
#include
#include
#include
#include
using namespace std;
// 商品信息
struct commodity{
string id;
string name;
double price;
int num;
commodity(string id_, string name_, double price_, int num_) :
id(id_), name(name_), price(price_), num(num_) {}
commodity() {}
};
// 从二进制文件内写出信息
void ReadFile(string filename, int num) {
ifstream file(filename, ios::binary);
// 存储信息
commodity s;
// 寻找第num种商品的信息
int index = 0;
while (file.read((char*)(&s), sizeof(s))) {
index++;
if (index == num)
break;
}
file.close();
// 显示信息
if (index == num) {
cout << std::left << setw(8) << "ID" << setw(8) << "Name" << setw(8) << "Num" << setw(8) << "Price" << endl;
cout << setw(8) << s.id << setw(8) << s.name << setw(8) <<
s.num << setw(8) << s.price << endl;
}
else {
cout << "No Find!" << endl;
}
}
int main() {
// 二进制文件文件路径
string path = "bf.bin";
int num;
cin >> num;
ReadFile(path, num);
return EXIT_SUCCESS;
}
我们查找第二件商品(存在)和第六件商品(不存在)
结果如下:
2
ID Name Num Price
002 电池 20 99.78
请按任意键继续. . .
6
No Find!
请按任意键继续. . .
验证测试实验表明,程序执行正确。