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
方法1:用map來求解獎勵map<int,int> cnt 作為數字與出現次數的映射關系
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <string.h>
#include <math.h>
using namespace std;
int main(){
int n,m,col;
map<int,int> cnt;
scanf("%d%d",&m,&n);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
scanf("%d",&col);
if(cnt.find(col)!=cnt.end()){
cnt[col]++;//若已存在就次數加一
}else{
cnt[col]=1;//若不存在次數置為1
}
}
}
int k=0,MAX=0;//最大數字及該數字出現次數
for(map<int,int>::iterator it=cnt.begin();it!=cnt.end();it++){
if(it->second>MAX){
k=it->first;
MAX=it->second;
}
}
printf("%d\n",k);
// system("pause");
return 0;
}
方法2:設定cnt和ans,cnt負責計數,ans負責記錄答案,遇到相等的cnt加1,遇到不等的cnt減1,當cnt變為0時,将ans換為新的數,cnt重置為1
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <string.h>
#include <math.h>
using namespace std;
int main()
{
int n, m, col;
scanf("%d%d", &m, &n);
int ans, cnt; //ans為衆數,cnt為這個數出現的次數
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
scanf("%d", &col);
if (i == 0 && j == 0)
{
cnt = 1;
ans = col;
}
else
{
if (col == ans)//如果依舊是這個數
{
cnt++;
}
else//如果不是這個數
{
cnt--;
if (cnt == 0)
{ //如果cnt為0令新數字為ans
ans = col;
cnt++; //cnt重新置為1
}
}
}
}
}
printf("%d\n",ans);
// system("pause");
return 0;
}