浙大pat 1054 题解

1054. The Dominant Color (20)

时间限制
100 ms
内存限制
32000 kB
代码长度限制
16000 B
判题程序
Standard

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, 800x600), 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


通过查找,每次从列表中除去两个不一样的数,最后就可以得出这个数,时间复杂度O(N)。写法上也有技巧,不必非要找到一个不一样的在继续下去,如果下一个一样,那么用一个变量记录这个次数,把次数+1,遇见不一样的-1。例如1,1,2,3,4 初始value =1,count =1,第二个1,value = 1,count =2,下一个2,value=1,count=1,下一个3,value=3,count=0,下一个4,value=4,count=1...一直到最后,看下value的值,就是所要找的数。

#include"iostream"
#include "algorithm"
#include <string>
#include "cstring"
#include"sstream"
using namespace std;

 

int main()
{
int m,n;
scanf("%d%d",&m,&n);

int Times=0,value;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
int num;
scanf("%d",&num);//用cin会超时
if(Times ==0)
{
value = num;
Times++;
}
else
{
if(num == value)
Times++;
else
Times--;
}

}
printf("%d\n",value);

return 0;
}

posted @ 2013-09-12 20:25  路萧  阅读(349)  评论(0编辑  收藏  举报