题意:简单的字符串处理与插入排序。难度:1星。
从文件读取字符串数据之后,模拟插入排序过程,计算插入次数,再将计数输出到文件。
需要注意:
1)C++的文件操作;
2)从文件读取时,在读取了int型数据之后,如果要getline(),则需要在两句中间加上get()以吸收int数据后的换行符;
题解代码:
/*
* Moist - Practice Round China New Grad Test 2014
*
* 字符串处理与模拟插入排序过程;
*
*/
#include <iostream>
#include <fstream>
using namespace std;
#define MAX_NAME_LENGTH 100
#define MAX_NAME_NUMBER 100
void InsertSort(char nameList[][MAX_NAME_LENGTH], int low, int high);
int main()
{
ifstream inputFile;
ofstream outputFile;
int T, N, cnt;
char nameList[MAX_NAME_NUMBER][MAX_NAME_LENGTH];
int i, j;
inputFile.open("E:\\C++\\GCJ\\China New Grad Test 2014\\Practice Round\\Moist\\C-small-practice-2.in");
outputFile.open("E:\\C++\\GCJ\\China New Grad Test 2014\\Practice Round\\Moist\\C-small-practice-2.out");
inputFile >> T;
for (i = 0; i < T; i++)
{
inputFile >> N;
inputFile.get(); /* 输入int型之后 && getline()之前,需要用get()吸收一个换行符 */
for (j = 0; j < N; j++)
{
inputFile.getline(nameList[j], MAX_NAME_LENGTH);
}
for (j = 0, cnt = 0; j < N - 1; j++)
{
if (strcmp(nameList[j], nameList[j + 1]) > 0)
{
cnt++;
InsertSort(nameList, 0, j + 1);
}
}//for (j = 0, cnt = 0; j < N - 1; j++)
cout << cnt << endl;
outputFile << "Case #" << i + 1 << ": " << cnt << endl;
}//for (i = 0; i < T; i++)
inputFile.close();
outputFile.close();
system("pause");
return 0;
}
void InsertSort(char nameList[][MAX_NAME_LENGTH], int low, int high)
{ /* 升序插入排序 */
/* nameList[low, high - 1][MAX_NAME_LENGTH]已有序,将nameList[high]插入 */
while (high > low && strcmp(nameList[high], nameList[high - 1]) < 0)
{
char tmp[MAX_NAME_LENGTH];
strcpy(tmp, nameList[high]);
strcpy(nameList[high], nameList[high - 1]);
strcpy(nameList[high - 1], tmp);
high--;
}
}