1054 The Dominant Color (20 分)

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^24是很大的数字,还算成了2*10^24!结果该数不能用long long表示,我甚至因此写了string,结果:超时

正解:2^24=16777216 不超过8位数 可用int表达

思考:我们可以看到PAT其实第一题考的并不难,数据也并不大,所以看题一定要细心+信心,并注意解题的技巧

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

const int N = 16777216+1;
int a[N];

int main()
{
    int n,m;
    cin >>m>>n;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            int x;
            cin >> x;
            a[x]++;
            if(a[x]>n*m/2){//解题技巧 有且只有一个数出现次数大于一半的格子数 该数就是答案
                cout << x;
                return 0;
            }
        }
    }
    return 0;
}

附第一次看错题写的超时18分代码:

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

struct node
{
    string num;
    int times;
    node(string num, int times):num(num),times(times){}
    node(){}
};

bool cmp(const node &a, const node &b)
{
    return a.times > b.times;
}

vector<node> v;

int n,m;

int main()
{
    string s;
    cin >>m>>n;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < m; j++){
            cin >> s;
            bool FIND = false;
            for(int i = 0; i < v.size(); i++){
                if(s==v[i].num){
                    v[i].times++;
                    FIND = true;
                    break;
                }
            }
            if(!FIND){
                v.push_back(node(s,0));
            }

        }
    }
    sort(v.begin(),v.end(),cmp);
    cout << v[0].num;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_36313227/article/details/89025733