第一题,我试了很多次最后例子只通过了70%,运行超时可是当时怎么也想不出来了,先记录下,懒得看题解,以后再想,
给定一个队列,但是这个队列比较特殊,可以从头部添加数据,也可以从尾部添加数据,但是只能从头部删除数据。输入一个数字n,会依次添加数字1~n(也就是添加n次)。
但是在添加数据的过程中,也会删除数据,要求删除必须按照1~n按照顺序进行删除,所以在删除时,可以根据需要调整队列中数字的顺序以满足删除条件。
输入描述:第一行一个数据N,表示数据的范围。
接下来的2N行是添加和删除语句。其中:head add x 表示从头部添加元素 x,tail add
表示从尾部添加元素,remove表示删除元素。输出描述:
输出一个数字,表示最小的调整顺序次数。
示例:
5 head add 1 tail add 2 remove head add 3 tail add 4 head add 5 remove
remove remove remove输出:
1
说明:
第1步:[1]
第2步:[1,2]
第3步:头部删除1,无需调整,还剩[2]
第4步:[3,2]
第5步:[3,2,4]
第6步:[5,3,2,4]
第7步:头部删除2,调整顺序再删除,还剩[3,4,5]
第8步:头部删除3,无需调整,还剩[4,5]
第9步:头部删除4,无需调整,还剩[5]
第10步:头部删除5,无需调整
只需要调整1次
#include <iostream>
#include <vector>
#include <deque>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
using namespace std;
int main() {
int n;
cin >> n;
string tempCmd;
// 猜测,对队列排序太慢导致超时
deque<int> que;
int tempCunt = 0;
int curShouldPopNum = 1;
for (int i = 0; i < 2 * n; i++) {
getline(cin, tempCmd);
if (tempCmd == "remove") {
if (que.front() != curShouldPopNum) {
tempCunt++;
vector<int> tempArr(que.begin(), que.end());
sort(tempArr.begin(), tempArr.end());
que = deque<int>(tempArr.begin(), tempArr.end());
//sort(que.begin(), que.end());
}
que.pop_front();
curShouldPopNum++;
}
else if (tempCmd.substr(0, 4) == "head") {
int j;
for (j = tempCmd.size() - 1; j >= 0; j--) {
if (tempCmd[j] == ' ')
break;
}
int tempNumSize = tempCmd.size() - j;
int tempNum = stoi(tempCmd.substr(j + 1, tempNumSize));
que.push_front(tempNum);
}
else if (tempCmd.substr(0, 4) == "tail") {
int j;
for (j = tempCmd.size() - 1; j >= 0; j--) {
if (tempCmd[j] == ' ')
break;
}
int tempNumSize = tempCmd.size() - j;
int tempNum = stoi(tempCmd.substr(j + 1, tempNumSize));
que.push_back(tempNum);
}
}
cout << tempCunt;
return 0;
}
另外两道都AC了,都很简单,第三题我以为会很难没想到一次过,第二题也挺简单的,无脑暴力
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int N;
cin >> N;
vector<int> arr(N);
for (int i = 0; i < N; i++)
{
cin >> arr[i];
}
int minPath = 2147483647;
int curLoc = arr[0];
sort(arr.begin(), arr.end());
for (int i = 0; i < N; i++) {
int sum = 0;
for (int j = 0; j < N; j++)
{
sum += abs(arr[i] - arr[j]);
}
if (sum < minPath)
{
minPath = sum;
curLoc = arr[i];
}
}
cout << curLoc;
return 0;
}
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <utility>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
map<string, string> strMap;
vector<string> res;
for (int i = 0; i < n; i++)
{
string tempStr;
cin >> tempStr;
string tempStr2 = tempStr;
sort(tempStr2.begin(), tempStr2.end());
strMap.insert(pair<string, string>(tempStr, tempStr2));
}
string tobe_cmpStr;
cin >> tobe_cmpStr;
sort(tobe_cmpStr.begin(), tobe_cmpStr.end());
bool haveIt = false;
for (auto x : strMap)
{
if (tobe_cmpStr == x.second)
{
haveIt = true;
res.push_back(x.first);
}
}
sort(res.begin(), res.end());
for (auto x : res)
{
cout << x << " ";
}
if (!haveIt)
{
cout << "null";
}
}