跳到正文

题解

题解:B3982 [信息与未来 2024] 数据排序

小睿2012约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年4月17日
篇幅
约 5 分钟
题目
B3982

版本

  1. v1当前

这道题是一道模拟题,做的时候要有耐心,我的做法分为以下 44 步。

一、读入表格,分类处理

先直接读入标题行,以 , 为间隔,提取每一栏的标题,并存放在数组中。然后,读入其余内容,以 , 和换行符 \n 为间隔读入字符信息并存放在数组中,如果读到字符,则那一格为字符串单元格,否则为数值单元格。

二、读入排序要求

直接读入,并存放在数组中即可。

三、排序

按照排序要求的输入顺序,找出那一个排序依据列的列号,并依据排序要求进行比较,如相同则跳过。如果存在所有排序依据列的值都与另一行相等的行,则按行号排序,保持与输入相同的相对顺序。

四、输出

按根据单元格内容及排序依据,排序后的行索引输出表格。

给出代码(有注释):

C++
#include <bits/stdc++.h>
using namespace std;

struct node
{
	bool op;//字符串 0 数字 1
	int x;
	string s;
}g[105][105];
string py[105];
bool sj[105];//0 降,1 升
int n,m,z,d[105];
int ls = 1;//列数

int fid(string s)//查找列
{
	for(int i = 1;i <= ls;i++)
		if(g[0][i].s == s)
		{
			return i;
		}
}

node got()//输入单元格
{
	node y = {1,0,""};
	char ch = getchar();
	string ss;
	while(1)
	{
		if(ch == ',' || ch == '\n')//该单元格输入完成
			break;
		ss += ch;
		if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
		{
			y.op = 0;	//如果有字母,代表是字符串单元格,打标记
		}
		ch = getchar();
	}
	if(y.op == 0)
	{
		y.s = ss;
	}
	else
	{
		if(ss.size() > 0)//转为整数
			y.x = stoi(ss);
	}
	return y;
}

bool cmp(int a,int b)
{
	for(int i = 1;i <= m;i++)
	{
		int dl = fid(py[i]);
		node da = g[a][dl];
		node db = g[b][dl];
		if(da.op)//数字类型
        {
			if(da.x != db.x)
			{
				if(sj[i]) return da.x < db.x;
				else return db.x < da.x;
			}
        }
		else//字符串类型
        {
			if(da.s != db.s)
			{
				if(sj[i]) return da.s < db.s;
				else return db.s < da.s;
			}
        }
	}
	return a < b;
}


int main()
{
	cin >> n;
	cin.ignore();//吞掉'\n'
	string l;
	getline(cin,l);
	cout << l << endl;//将标题行输出
	int llen = l.size();
	for(int i = 0;i < llen;i++)
	{
		if(l[i] == ',')
		{
			ls++;
		}
		else
		{
			g[0][ls].s += l[i];
		}
	}
	for(int i = 1;i < n;i++)//输入单元格
		for(int j = 1;j <= ls;j++)
		{
			g[i][j] = got();
		}
	cin >> m;
	for(int i = 1;i <= m;i++)//输入排序要求
	{
		string sr;
		cin >> sr;
		int srl = sr.size();
		char zz = sr[srl - 1];
		if(zz == '-')
			sj[i] = 0;
		else
			sj[i] = 1;
		py[i] = sr.substr(0,srl - 1);
	}
	for(int i = 1;i < n;i++) d[i] = i;//存储行索引
	sort(d + 1,d + n,cmp);//排序
	for(int i = 1;i < n;i++)//输出
	{
		for(int j = 1;j <= ls;j++)
		{
			if(g[d[i]][j].op)
				cout << g[d[i]][j].x;
			else
				cout << g[d[i]][j].s;
			if(j != ls)
			{
				cout << ',';
			}
		}
		cout << '\n';
	}
	return 0;
}

AC记录

原文