2020.09.12.vivo秋招笔试(3题1h)
第一题:AC70% n*n的矩阵,从一点走到另一点的最短路径,# @都是障碍物,其他的都是可以走,求最短的步数
思路:从起点开始,直接bfs开始搜索,到了第一次到了终点直接返回答案;
思路:从起点开始,直接bfs开始搜索,到了第一次到了终点直接返回答案;
(写完代码提交就只剩了5min了,没时间调试,希望路过的大佬可以提供下第一题的思路,或者哪里细节忽略了。非常感谢!)
(这是更新内容):卡70%的原因就是题目给的坐标是y x y x, 然后我当做x y x y来处理的。
为啥题目要这么搞我们啊!!!!!!!谁出的这数据!!!!!故意留这个坑有用吗??????(差一步就AK)
代码:
#include<bits/stdc++.h>
using namespace std;
#define ios ios::sync_with_stdio(false),cin.tie(0);
using pii = pair<int,int>;
const int maxn = 10005;
int dirs[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
bool d[maxn][maxn];
string strs[maxn];
int n;
pii src;
pii dst;
void bfs() {
queue<pair<pii,int>> q;
q.push({src, 0});
d[src.first][src.second] = true;
while(!q.empty()) {
pair<pii,int> cur = q.front();
q.pop();
if(cur.first == dst) {
cout << cur.second << endl;
return;
}
for(int i = 0; i < 4; ++i) {
int x = dirs[i][0] + cur.first.first;
int y = dirs[i][1] + cur.first.second;
if(x < 0 || y < 0 || x >= n || y >= n) continue;
if(strs[x][y] == '@' || strs[x][y] == '#' || d[x][y]) continue;
q.push({{x,y}, cur.second+1});
d[x][y] = true;
}
}
}
int main(void)
{
#ifndef ONLINE_JUDGE
freopen("a.txt", "r", stdin);
#endif
while(cin >> n) {
cin >> src.first >> src.second >> dst.first >> dst.second;
for(int i = 0; i < n; ++i) cin >> strs[i];
memset(d, 0, sizeof(d));
bfs();
}
return 0;
} 第二题:AC100% 给一个字符串,如果去掉一个字符可以构成回文,就输出那个答案,输出删除最左端的那个字符的回文答案
思路:直接暴力计算,从左开始依次试探,看是否构成回文,如果成功就直接输出答案
代码:
#include<bits/stdc++.h>
using namespace std;
#define ios ios::sync_with_stdio(false),cin.tie(0);
bool ispalind(string& s, int l, int r, int k) {
while(l < r) {
if(l == k) {
l++;
if(l < r && s[l] != s[r]) return false;
} else if(r == k) {
r--;
if(l < r && s[l] != s[r]) return false;
} else {
if(s[l] != s[r]) return false;
}
l++;
r--;
}
return true;
}
int main(void)
{
#ifndef ONLINE_JUDGE
freopen("b.txt", "r", stdin);
#endif
int n;
string s;
while(cin >> s) {
int n = s.size();
bool found = false;
for(int i = 0; i < n; ++i) {
if(ispalind(s, 0, n-1, i)) {
cout << s.substr(0, i) + s.substr(i+1, n-i-1) << endl;
found = true;
break;
}
}
if(!found) cout << "false" << endl;
}
return 0;
}
第三题:AC100% 给一个有向树,输出字典序最小的那个拓扑排序
思路:用小根堆的优先队列依次遍历即可
代码:
class Solution {
vector<int> a;
int n;
void getInt(string s) {
stringstream ss(s);
while(getline(ss, s, ',')) a.push_back(atoi(s.c_str()));
}
public:
string compileSeq(string input) {
a.clear();
getInt(input);
n = a.size();
string ans;
vector<int> indeg(n+1);
vector<vector<int>> tree(n);
for(int i = 0; i < n; ++i) {
if(a[i] == -1) continue;
tree[a[i]].push_back(i);
indeg[i]++;
}
priority_queue<int, vector<int>, greater<int>> heap;
for(int i = 0; i < n; ++i) {
if(indeg[i] == 0) heap.push(i);
}
while(!heap.empty()) {
int cur = heap.top();
heap.pop();
if(ans.size() == 0) ans.append(to_string(cur));
else ans.append(",").append(to_string(cur));
for(int v : tree[cur]) {
if((--indeg[v]) == 0) {
heap.push(v);
}
}
}
return ans;
}
}; 
