某种聊天工具,每个好友的id都是唯一的,当用户接收到信息后,如果会话窗口之前没有与该好友的聊天信息,则在通信列表里,会将新接收的消息的好友id置顶,如果会话窗口中已有与该好友的聊天信息,则将该好友的id移动到通讯列表的顶端。请根据要求实现该功能。 输入:第一行为整数N,代表有N组测试数据,接下来的N组测试中,第一行为整数T,代表有T条通讯,第二行有T个整数,按时间先后顺序表示接收到讯息的好友id。 输出:按照通讯列表从上到下的顺序输出好友id,每个id以空格分隔C++
时间: 2024-02-28 22:55:22 浏览: 25
以下是实现该功能的C++代码:
```cpp
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int main() {
int n;
cin >> n;
while (n--) {
int t;
cin >> t;
vector<int> ids(t);
for (int i = 0; i < t; i++) {
cin >> ids[i];
}
vector<int> list;
unordered_map<int, int> pos;
for (int i = 0; i < t; i++) {
int id = ids[i];
if (pos.count(id) == 0) {
list.insert(list.begin(), id);
pos[id] = 0;
} else {
int p = pos[id];
list.erase(list.begin() + p);
list.insert(list.begin(), id);
}
for (int j = 0; j < list.size(); j++) {
pos[list[j]] = j;
}
}
for (int i = 0; i < list.size(); i++) {
cout << list[i] << " ";
}
cout << endl;
}
return 0;
}
```
对于每组测试数据,我们首先读入T条通讯的好友id,并使用vector `ids` 存储。接下来,我们使用vector `list` 来存储当前的通讯列表,使用unordered_map `pos` 来记录每个好友id在通讯列表中的位置。
对于接收到的每个好友id,我们先判断该好友id是否已经在通讯列表中。如果不在,我们将该好友id插入到通讯列表的最顶端,并将其位置记录在unordered_map `pos` 中。如果已经在,我们找到该好友id在通讯列表中的位置,并将该好友id移动到通讯列表的最顶端。
最后,我们输出通讯列表中的所有好友id即可。注意,在移动好友id时,我们需要更新unordered_map `pos` 中所有好友id的位置信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)