题解 AT315 【おとぎの国の高橋君】
Update:2020.11.5 新增运算符重载代码
本题还真是有意思!
我的思路是这样的
对于输入的顺序,将这些顺序先储存起来
然后输入时做一个类,类中包含一个数字和一个类似运算符重载的小于函数is_small,参数有两个,两个类
对于这两个类,转成字符串做比较,先看长度,长度一样一位位比较
附上AC代码(好像我这个内存和时间都比大家多,哇)
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int mp[15];
class Cla
{
public:
int a;
bool is_small(Cla g, Cla h)
{
string x = to_string(g.a), y = to_string(h.a);
int len = x.length(), len2 = y.length();
if(len > len2)
{
return false;
}
else if(len < len2)
{
return true;
}
else
{
len--;
len2--;
for(int i = 0; i <= len; i++)
{
if(mp[x[i] - '0'] < mp[y[i] - '0'])
{
return true;
}
else if(mp[x[i] - '0'] > mp[y[i] - '0'])
{
return false;
}
}
return true;
}
}
};
Cla a[790], s;
bool cmp(Cla x, Cla y)
{
return s.is_small(x, y);
}
int main()
{
for(int i = 1; i <= 10; i++)
{
int x;
cin >> x;
mp[x] = i;
}
int n;
cin >> n;
for(int i = 1; i <= n; i++)
{
cin >> a[i].a;
}
sort(a + 1, a + n + 1, cmp);
for(int i = 1; i <= n; i++)
{
cout << a[i].a << endl;
}
return 0;
}
但这个代码的效率比较低,其原因在于to_string(),这样写的话每次转string很慢
那直接写成string更好,还有我们上面讲过运算符重载,那我们也可以用运算符重载做
那你肯定会问,运算符重载不是只支持一个参数吗?对比两个类怎么做?
那你肯定是不知道友元函数
友元是支持两个参数的哦
注意,友元函数是定义在类外,所以如果用operator <(x, y)的话不要再operator前加‘类.’做访问
那么,代码不就简单了吗?速度快了几十ms
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int mp[15];
class Cla
{
public:
string a;
friend bool operator <(const Cla &x, const Cla &y)//友元需在返回类型前加上friend
{
int len = x.a.length(), len2 = y.a.length();
if(len > len2)
{
return false;
}
else if(len < len2)
{
return true;
}
else
{
len--;
len2--;
for(int i = 0; i <= len; i++)
{
if(mp[x.a[i] - '0'] < mp[y.a[i] - '0'])
{
return true;
}
else if(mp[x.a[i] - '0'] > mp[y.a[i] - '0'])
{
return false;
}
}
return true;
}
}
};
Cla a[790];
bool cmp(Cla x, Cla y)
{
return x < y;//也可以写成operator <(x, y);
}
int main()
{
for(int i = 1; i <= 10; i++)
{
int x;
cin >> x;
mp[x] = i;
}
int n;
cin >> n;
for(int i = 1; i <= n; i++)
{
cin >> a[i].a;
}
sort(a + 1, a + n + 1, cmp);
for(int i = 1; i <= n; i++)
{
cout << a[i].a << endl;
}
return 0;
}
分类:
题解
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现