一、题目
【深基15.例2】寄包柜
题目描述
超市里有 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 数据。
二、题解
- 基本思路:每次查询根据第几个寄包柜的第几个格子找到物品,这里我开了一个结构体数组用来表示寄包柜,下标i为第几个寄包柜,用哈希的目的是建立格子到物品的映射。
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define endl "\n"
#define int long long
#define fi first
#define se second
#define lb lower_bound
#define ub upper_bound
#define gcd __gcd
#define repn(i,a,n) for(int i = a; i <= n; i++)
#define rep(i,a,n) for(int i = a; i < n; i++)
typedef pair<int,int> PII;
struct Info{
unordered_map<int,int> mp;//格子到物品的映射
}s[100010];//第几个寄包柜
void solve(){
int n,q;
cin>>n>>q;
while(q--){
int op; cin>>op;
if(op==1){
int i,j,k;
cin>>i>>j>>k;
s[i].mp[j]=k;
}else{
int i,j;
cin>>i>>j;
cout<<s[i].mp[j]<<endl;
}
}
}
signed main(){
IOS;
int T=1;
while(T--){
solve();
}
return 0;
}
- 也可以哈希嵌套哈希的方式写,代码如下
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define endl "\n"
#define int long long
#define fi first
#define se second
#define lb lower_bound
#define ub upper_bound
#define gcd __gcd
#define repn(i,a,n) for(int i = a; i <= n; i++)
#define rep(i,a,n) for(int i = a; i < n; i++)
typedef pair<int,int> PII;
void solve(){
int n,q;
cin>>n>>q;
unordered_map<int,unordered_map<int,int>> hash;
while(q--){
int op; cin>>op;
if(op==1){
int i,j,k;
cin>>i>>j>>k;
hash[i][j]=k;
}else{
int i,j;
cin>>i>>j;
cout<<hash[i][j]<<endl;
}
}
}
signed main(){
IOS;
int T=1;
while(T--){
solve();
}
return 0;
}