文章目录
- 1 题目
- 2 解析
- 2.1 题意
- 2.2 思路
- 2.2.1 思路一(map数组)
- 2.2.2 思路二(不用map数组)
- 3 参考代码
- 3.1思路一
- 3.2 思路二
1 题目
1054 The Dominant Color (20分)
Behind the scenes in the computer’s memory, color is always talked about as a series of 24 bits of information for each pixel. In an image, the color with the largest proportional area is called the dominant color. A strictly dominant color takes more than half of the total area. Now given an image of resolution M by N (for example, 800×600), you are supposed to point out the strictly dominant color.
Input Specification:
Each input file contains one test case. For each case, the first line contains 2 positive numbers: M (≤800) and N (≤600) which are the resolutions of the image. Then N lines follow, each contains M digital colors in the range [0,2
24
). It is guaranteed that the strictly dominant color exists for each input image. All the numbers in a line are separated by a space.
Output Specification:
For each test case, simply print the dominant color in a line.
Sample Input:
5 3
0 0 255 16777215 24
24 24 0 0 24
24 0 24 24 24
Sample Output:
24
2 解析
2.1 题意
统计矩阵块中,最占优势的颜色(出现次数最多的颜色)
2.2 思路
2.2.1 思路一(map数组)
如果直接开一个int类型hash数组,由于数字范围最大可达16777216,可能会导致内存空间超限,因此可以使用map<int,int>进行映射,对于每次输入的值用find函数查找是否出现过,如果出现过则加一,否则将值赋值为1。
2.2.2 思路二(不用map数组)
由于题目最优颜色的数量要求超过半数,因此有超过半数的数相同,如果采用两两不同相互抵消的做法。
- 设置一个ans记录答案,count统计ans出现的次数,
- 然后在读入时,判断ans与读入的数字是否相同,如果不想等,则抵消一次(即令count减1),如果相等,则令count加1。如果某步count被抵消到0,令新的数字为ans。最后剩下的ans就是答案。
3 参考代码
3.1思路一
#include
#include
using std::map;
map<int , int> count;
int main(int argc, char const *argv[])
{
int m, n;
scanf("%d%d", &m , &n);
int num;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
scanf("%d", &num);
if(count.find(num) != count.end()){
count[num]++;
}else{
count[num] = 1;
}
}
}
int max = -1, idx = 0;
for (map<int,int>::iterator it = count.begin(); it != count.end(); ++it)
{
if(it->second > max){
max = it->second;
idx = it->first;
}
}
printf("%d\n", idx);
return 0;
}
3.2 思路二
/*
3 2
4502761 4502761
4502761 4502761
7340438 3208719
*/
#include
int main(int argc, char const *argv[])
{
int n, m;
scanf("%d%d", &n, &m);
int num;
int count = 1, ans = -1;
for(int i = 0; i < n * m; i++){
scanf("%d", &num);
if(ans != num){
count--;
}else{
count++;
}
if(count == 0){
ans = num;
count++;
}
}
printf("%d\n", ans);
return 0;
}