题目描述
超市里有 n ( 1 ≤ n ≤ 1 0 5 ) n(1\le n\le10^5) n(1≤n≤105) 个寄包柜。每个寄包柜格子数量不一,第 i i i 个寄包柜有 a i ( 1 ≤ a i ≤ 1 0 5 ) a_i(1\le a_i\le10^5) ai(1≤ai≤105) 个格子,不过我们并不知道各个 a i a_i ai 的值。对于每个寄包柜,格子编号从 1 开始,一直到 a i a_i ai。现在有 q ( 1 ≤ q ≤ 1 0 5 ) q(1 \le q\le10^5) q(1≤q≤105) 次操作:
1 i j k
:在第 i i i 个柜子的第 j j j 个格子存入物品 k ( 0 ≤ k ≤ 1 0 9 ) k(0\le k\le 10^9) k(0≤k≤109)。当 k = 0 k=0 k=0 时说明清空该格子。2 i j
:查询第 i i i 个柜子的第 j j j 个格子中的物品是什么,保证查询的柜子有存过东西。
已知超市里共计不会超过 1 0 7 10^7 107 个寄包格子, a i a_i ai 是确定然而未知的,但是保证一定不小于该柜子存物品请求的格子编号的最大值。当然也有可能某些寄包柜中一个格子都没有。
输入格式
第一行 2 个整数 n n n 和 q q q,寄包柜个数和询问次数。
接下来 q q q 个整数,表示一次操作。
输出格式
对于查询操作时,输出答案,以换行隔开。
样例 #1
样例输入 #1
5 4
1 3 10000 118014
1 1 1 1
2 3 10000
2 1 1
样例输出 #1
118014
1
提示
upd 2022.7.26 \text{upd 2022.7.26} upd 2022.7.26:新增加一组 Hack 数据。
解题思路:
读完题之后,很快可以想到将柜子和格子抽象为二维数组,但又很快发现会导致MLE
这时候就会发现,本质上我们要做的就是实现两个索引确定的一个元素
可以使用STL中的map来实现
首先构建一个索引的结构体:
struct map_index
{
int m_i;
int m_j;
};
然后创建一个map容器:
map<map_index, int>cabinet;
最后很容易实现输入、处理和输出的操作:
int main()
{
map<map_index, int>cabinet;
int n, q;
cin >> n >> q;
int select, item;//用于读入选项、要存入的数字
struct map_index temp_map_index;//用于读入map的索引
for (int i = 0; i < q; i++)
{
cin >> select;
if (select == 1)//存入
{
cin >> temp_map_index.m_i >> temp_map_index.m_j >> item;
cabinet.insert(pair<map_index, int>(temp_map_index, item));
}
else if (select == 2)//读取
{
cin >> temp_map_index.m_i >> temp_map_index.m_j;
cout << cabinet.find(temp_map_index)->second << endl;
}
}
return 0;
}
当然,还没有结束
直接运行会报错,因为map默认的排序规则并不能应用于我们创建的索引类型
我们就需要自己来写一个排序的函数:
class MyCompare
{
public:
//写一个重载函数调用运算符(仿函数),实现升序排序
bool operator()(struct map_index m_i_1, struct map_index m_i_2)const//这里如果不加const,部分编译器会报错
{
if (m_i_1.m_i < m_i_2.m_i)
{
return true;
}
else if (m_i_1.m_i > m_i_2.m_i)
{
return false;
}
else
{
if (m_i_1.m_j < m_i_2.m_j)
{
return true;
}
else
{
return false;
}
}
}
};
第二个错误点就是没有考虑到对同一个柜子的格子(索引)会进行更新操作
第二次插入相同的索引时,会插入失败,不会更新item的值
改正后完整的代码如下:
#include <iostream>
#include <map>
using namespace std;
struct map_index
{
int m_i;
int m_j;
};
class MyCompare
{
public:
bool operator()(struct map_index m_i_1, struct map_index m_i_2)const
{
if (m_i_1.m_i < m_i_2.m_i)
{
return true;
}
else if (m_i_1.m_i > m_i_2.m_i)
{
return false;
}
else
{
if (m_i_1.m_j < m_i_2.m_j)
{
return true;
}
else
{
return false;
}
}
}
};
int main()
{
map<map_index, int, MyCompare>cabinet;//传入自定义的排序类
int n, q;
cin >> n >> q;
int select, item;
struct map_index temp_map_index;
for (int i = 0; i < q; i++)
{
cin >> select;
if (select == 1)
{
cin >> temp_map_index.m_i >> temp_map_index.m_j >> item;
if(cabinet.find(temp_map_index) == cabinet.end())
{
cabinet.insert(pair<map_index, int>(temp_map_index, item));
}
else
{
cabinet.find(temp_map_index)->second = item;
}
}
else if (select == 2)
{
cin >> temp_map_index.m_i >> temp_map_index.m_j;
cout << cabinet.find(temp_map_index)->second << endl;
}
}
return 0;
}