1054 The Dominant Color (20 point(s)) - C语言 PAT 甲级

1054 The Dominant Color (20 point(s))

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, 224). 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

题目大意:

选取图像的主色,主色是颜色占据总面积一半以上的颜色,也就是在输入的 M 列 N 行的矩阵中,寻找出现次数多于一半的数字

题目保证输入的数据中一定有主色

设计思路:

思路 2(计数):

  • 用 num 保存当前数字,count 表示数字出现的次数
  • 当 下一个数字等于 num 时,count++,否则 count–
  • 当 count == 0 时,num 重新保存当前数字
  • 最终 num 保存的一定是出现次数最多的数字

思路 1(数组):

  • 用数组储存每个数字出现的次数,当次数大于一半时,输出此数字
编译器:C (gcc)
//思路 2(计数):
#include 

int main(void)
{
        int m, n;
        int count = 0, num, temp;
        int i, j;
        scanf("%d %d", &m, &n);
        for (i = 0; i < n; i++) {
                for (j = 0; j < m; j++) {
                        scanf("%d", &temp);
                        if (count == 0) {
                                num = temp;
                                count++;
                        } else {
                                if (temp == num) {
                                        count++;
                                } else {
                                        count--;
                                }
                        }
                }
        }
        printf("%d", num);
        return 0;
}

/*//思路 1(数组):
#include 

int hash[1 << 24] = {0};

int main(void)
{
        int m, n;
        int i, j, temp;
        scanf("%d %d", &m, &n);
        int half = m * n / 2;
        for (i = 0; i < n; i++) {
                for (j =  0; j < m; j++) {
                        scanf("%d", &temp);
                        hash[temp]++;
                        if (hash[temp] > half) {
                                printf("%d", temp);
                                return 0;
                        }
                }
        }
        return 0;
}
*/

你可能感兴趣的:(PAT,甲级)