9.11 JD京东编程2题解析(C++版本)
第一题:判断用特定键盘打字需要多久
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m, x, y, z;
cin >> n >> m >> x >> y >> z;
unordered_map<char, pair<int, int>> pos;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
char c;
cin >> c;
pos[c] = {i, j};
}
}
string str;
cin >> str;
int len = str.size();
long long ret = (long long)len * z;
pair<int, int> prePos = {0, 0};
for (int i = 0; i < len; i++) {
if (prePos.first == pos[str[i]].first && prePos.second == pos[str[i]].second) {
continue;
} else if (prePos.first != pos[str[i]].first && prePos.second != pos[str[i]].second) {
ret += y;
ret += (long long)x * (abs(prePos.first - pos[str[i]].first) + abs(prePos.second - pos[str[i]].second));
} else {
ret += (long long)x * (abs(prePos.first - pos[str[i]].first) + abs(prePos.second - pos[str[i]].second));
}
prePos = pos[str[i]];
}
cout << ret << endl;
return 0;
} 第二题:systemd判断每次启停任务后的任务存活数 #include <bits/stdc++.h>
using namespace std;
typedef struct Node{
bool doing = false;
vector<int> need;
vector<int> beNeed;
} Node;
int main() {
int n, q;
cin >> n >> q;
Node node[n];
for (int i = 0; i < n; i++) {
int c;
cin >> c;
for (int j = 0; j < c; j++) {
int cur;
cin >> cur;
node[i].need.push_back(cur - 1);
node[cur - 1].beNeed.push_back(i);
}
}
for (int i = 0; i < q; i++) {
int x, y;
cin >> x >> y;
if (x == 0) {
node[y - 1].doing = false;
int levelSize = 1;
queue<int> que;
que.push(y - 1);
while (levelSize) {
for (int k = 0; k < levelSize; k++) {
for (const auto& item : node[que.front()].beNeed) if (node[item].doing == true) que.push(item);
node[que.front()].doing = false;
que.pop();
}
levelSize = que.size();
}
} else if (x == 1) {
node[y - 1].doing = true;
int levelSize = 1;
queue<int> que;
que.push(y - 1);
while (levelSize) {
for (int k = 0; k < levelSize; k++) {
for (const auto& item : node[que.front()].need) if (node[item].doing == false) que.push(item);
node[que.front()].doing = true;
que.pop();
}
levelSize = que.size();
}
}
int ret = 0;
for (const auto& c : node) if (c.doing) ret++;
cout << ret << endl;
}
return 0;
}
查看14道真题和解析

