我的PAT-BASIC代码仓:https://github.com/617076674/PAT-BASIC
原题链接:https://pintia.cn/problem-sets/994805260223102976/problems/994805265579229184
题目描述:
知识点:记录map
思路:用一个map记录该数字是否出现过
如果开数组来记录该数字是否出现过,需要开一个大小为16777216的数组,这样提交会报“段错误”,因此我们改用map来记录。
注意点:
满足要求的点不仅要求色差足够大,而且要求独一无二!
本题有一个坑点:
虽然题目说——“并且该点的颜色与其周围8个相邻色素的颜色差充分大”,但其实四周的点也是需要考虑进去的。否则无法通过测试点3和5。
时间复杂度是O(M * N)。空间复杂度是O(n),其中n为输入矩阵中不同颜色的数量。
C++代码:
#include<iostream>
#include<vector>
#include<utility>
#include<math.h>
#include<map>
using namespace std;
bool isRedInGreen(int *p, int N, int M, int indexi, int indexj, int TOL);
int main(){
int M, N, TOL;
cin >> M >> N >> TOL;
int colors[N][M];
map<int, int> flags;
int tempColor;
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
scanf("%d", &tempColor);
colors[i][j] = tempColor;
if(flags.find(tempColor) != flags.end()){
flags[tempColor]++;
}else{
flags[tempColor] = 1;
}
}
}
vector<pair<int, int> > reds;
pair<int, int> tempPair;
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
if(isRedInGreen((int *)colors, N, M, i, j, TOL) && flags[colors[i][j]] == 1){
tempPair.first = i;
tempPair.second = j;
reds.push_back(tempPair);
}
}
}
if(reds.size() == 0){
cout << "Not Exist" << endl;
}else if(reds.size() > 1){
cout << "Not Unique" << endl;
}else{
int indexi = reds[0].first;
int indexj = reds[0].second;
cout << "(" << indexj + 1 << ", " << indexi + 1 << "): " << colors[indexi][indexj] << endl;
}
}
bool isRedInGreen(int *p, int N, int M, int indexi, int indexj, int TOL){
int directions[8][2] = {{1, 1}, {1, 0}, {1, -1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, 1}, {0, -1}};
for(int i = 0; i < 8; i++){
int newi = indexi + directions[i][0];
int newj = indexj + directions[i][1];
if(newi < 0 || newi >= N || newj < 0 || newj >= M){
continue;
}
int preColor = *(p + indexi * M + indexj);
int newColor = *(p + newi * M + newj);
if(abs(newColor - preColor) <= TOL){
return false;
}
}
return true;
}
C++解题报告: