PAT A1054

题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805422639136768

之前以为是大数,用的string映射int,结果用cin,cout超时。后来改成int映射int就不超时了。然后遇到一个问题,原来题目中说的dominant color大于一半,并不是。最后一个测试用例就小于一半,坑啊。我之前代码是这样的:

#include <cstdio>
#include <map>
using namespace std;
map<int, int> a;
int main(){
	int n, m;
	scanf("%d%d", &m, &n);
	int str;
	for(int i = 0; i < n; i++){
		for(int j = 0; j < m; j++){
			scanf("%d", &str);
			if(a.find(str) != a.end()){
				a[str]++;
				if(a[str] * 2 > m * n){
					printf("%d\n", str);
					return 0;
				}
			}
			else
				a[str] = 1;
		}
	}
}

最后一个用例打死都过不到,也考虑过是不是没有取等,因为可能只有两个颜色,结果最后一个用例还是错误,于是参考了算法笔记。它就没有利用大于一半这个条件,只是找最大值。然后结果就对了。

#include <cstdio>
#include <map>
using namespace std;
map<int, int> a;
int main(){
	int n, m;
	scanf("%d%d", &m, &n);
	int str;
	for(int i = 0; i < n; i++){
		for(int j = 0; j < m; j++){
			scanf("%d", &str);
			if(a.find(str) != a.end()){
				a[str]++;
				if(a[str] * 2 > m * n){
					printf("%d\n", str);
					return 0;
				}
			}
			else
				a[str] = 1;
		}
	}
	int max = -1, k;
	for(map<int, int>::iterator it = a.begin(); it != a.end(); it++){
		if(it->second > max){
			k = it->first;
			max = it->second;
		}
	}
	printf("%d\n", k);
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值