序言
此篇博客作为自己的学习笔记,同时欢迎大家交流!
题目
The winner of the card game popular in Berland “Berlogging” is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line “name score”, where name is a player’s name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It’s guaranteed that at the end of the game at least one player has a positive number of points.(加粗的地方是这个题目的关键,要首先第一个达到该分数的,并且还得最终仍是最大分数的那个人)
Input
The first line contains an integer number n (1 ≤ n ≤ 1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in “name score” format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.
Output
Print the name of the winner.
Examples
Input
3
mike 3
andrew 5
mike 2
Output
andrew
Input
3
andrew 3
andrew 2
mike 5
Output
andrew
代码
#include<iostream>
#include<cstring>
#include<algorithm>//习惯写上这三个头文件
#include<map>//map头文件
using namespace std;
map<string,int>ss,ss2;//声明两个map 一个记录最终得分,一个记录临时得分
int main()
{
int n;
cin>>n;
string name[n];
int num[n],mx=1e-7;//因为得分有可能为负数,所以以无穷小为最大值,不会出现错误
for(int i=0;i<n;i++)
{
cin>>name[i]>>num[i];
ss[name[i]]+=num[i];
}//第一个循环统计最终得分
for(int i=0;i<n;i++) mx=max(mx,ss[name[i]]);//第二个循环统计最终最大值
for(int i=0;i<n;i++)
{
ss2[name[i]]+=num[i];
if(ss2[name[i]]>=mx&&ss[name[i]]>=mx){
//第三个循环统计首先到达最大值并且最终仍然是最大值的那个字符串
cout<<name[i]<<endl;//输出该字符串
return 0;//停止该程序
}
}
}
可能有同学会有疑问,为什么不可以在循环的时候判断 比如:
for(int i=0;i<n;i++)
{
cin>>name[i]>>num[i];
ss[name[i]]+=num[i];
if(ss[name[i]]>=mx)
mx=ss[name[i]];
题目介绍中给出了,分数有可能为负数 (每次得到的分数在-1000到1000之间),所以有可能是在原来的基础上减去分数,比如最终的最大值是5,有可能这个人已经得到7分了,但最终减去了2分,为5,如果有这个循环判断的话,就会导致最大值是7,而不是5了,就会WA了;
(不要问我咋知道的,问就是我错过…)