本来算法题就是弱项,做哪道哪道不会,目前第一波笔试题已跪......HR小姐姐说可以一直刷,直到通过(有点残忍...)
卧薪尝胆,本人打算在这里一道道刚......真不信了!!!
第一题:
这道题是一道经典的深度优先搜索题,可以申请一个相同大小的额外空间来给变量过的元素标记。参考了别人的代码,https://blog.csdn.net/NichChen/article/details/81605200,不得不说,自己的C++还是不熟啊
void DFS(vector<vector<int> > &arr, vector<vector<bool>> &check, int &count, int i, int j){
if (i < 0 || i >= arr.size() || j < 0 || j >= arr[0].size())
return;
if (arr[i][j] == 1 && check[i][j] == false){
check[i][j] = true;
count++;
//因为是从左上到右下遍历,所以当前元素的 左方 和上方的元素早已遍历过了,这里无需再递归
//DFS(arr, check, count, i - 1, j - 1);
//DFS(arr, check, count, i - 1, j);
//DFS(arr, check, count, i, j - 1);
DFS(arr, check, count, i - 1, j + 1);
DFS(arr, check, count, i, j + 1);
DFS(arr, check, count, i + 1, j);
DFS(arr, check, count, i + 1, j - 1);
DFS(arr, check, count, i + 1, j + 1);
}
else{
return;
}
}
int main()
{
int m, n;
char commer;
cin >> m >> commer >> n;
vector<vector<int>> arr(m, vector<int>(n, 0));
vector<vector<bool>> check(m, vector<bool>(n, false));
int i = 0, j = 0;
vector<int> temp1(n, 0);
for (; i < m; i++){
j = 0;
for (; j < n - 1; j++){
cin >> temp1[j];
cin >> commer;
}
cin >> temp1[j];
arr[i] = temp1;
}
int lineAmount = 0, maxAmount = 0, tempAmount = 0;
for (i = 0; i < m; i++){
for (j = 0; j < n; j++){
if (arr[i][j] == 1 && check[i][j] == false){
lineAmount++;
DFS(arr, check, tempAmount, i, j);
maxAmount = max(maxAmount, tempAmount);
tempAmount = 0;
}
}
}
cout << lineAmount << " " << maxAmount;
cout << endl;
for (i = 0; i < m; i++){
for (j = 0; j < n; j++){
cout << check[i][j] << " ";
}
cout << endl;
}
return 0;
}
第二题
这道算是所有题目中比较简单的一道了,主要制定排序规则。
class NumList{
public:
NumList(int start, int end){
this->start = start;
this->end = end;
};
//重载 < 符号,注意,不能重载 > 因为sort里好像没用到 >,重载后导致编译不能通过。
bool operator< (const NumList& other){
if (this->start < other.start){
return true;
}
else{
return false;
}
}
int getValueStart(){
return start;
}
int getValueEnd(){
return end;
}
private:
int start;
int end;
};
void mergeList(vector<NumList>& arr){
if (arr.size() <= 0)
return;
sort(arr.begin(), arr.end());
vector<NumList*> result;
int start = arr[0].getValueStart();
int end = arr[0].getValueEnd();
for (int i = 0; i < arr.size() - 1; i++){
if (end >= arr[i + 1].getValueStart()){
end = arr[i + 1].getValueEnd();
}
else{
result.push_back(new NumList(start, end));
start = arr[i + 1].getValueStart();
end = arr[i + 1].getValueEnd();
}
}
result.push_back(new NumList(start, end));
for (NumList* b : result){
cout << b->getValueStart() << "," << b->getValueEnd() << endl;
}
for (NumList* b : result){
delete b;
}
}
int main(){
vector<NumList> arr;
int N;
cin >> N;
string s;
getline(cin, s);//读取上一行的回车
for (int i = 0; i < N; i++){
getline(cin, s);
istringstream is(s);
int start, end;
char commer, maohao;
while (is >> start >> commer >> end){
NumList a(start, end);
arr.push_back(a);
is >> maohao;
}
}
mergeList(arr);
return 0;
}