map–初级题目-寻找满足要求的最大值
题目链接
备注:在自己思考动手之后再看我下面分享的题目哦;
题目描述:
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.
Input
3
mike 3
andrew 5
mike 2
Output
andrew
Input
3
andrew 3
andrew 2
mike 5
Output
andrew
题目大意:
体现在输入输出:
输入:
第一行输入一个正整数n
第二到n+1行,每一行输入一串字符(名字)和这个字符对应的价值(可为负)
输出:输出一个名字
注:该名字满足以下要求:
1,这个名字的对应的价值最大;
2,如果有和这个名字相同价值的,那么这个名字的价值应该是最早体现出来这个最大价值的;
注:代码由c和c++混合
#include<iostream>
#include<string>
#include<map>
#define INF 0x3f3f3f3f
using namespace std;
int main()
{
int n;
scanf("%d",&n);//行数n
string str[1010];//保存姓名;
int temp[1010];//保存价值;
int i;
int maxm;
map<string,int>m;
map<string,int>m1;
for(i=0;i<n;i++)//读入数据,并计算出对应姓名的价值;
{
cin>>str[i]>>temp[i];
m[str[i]]+=temp[i];//尝试在读入数据的时候就计算出最大值,没有ac,好奇怪!
}
map<string,int>::iterator ite;//开始寻找,找到最大的价值;
for(ite=m.begin(),maxm=-INF;ite!=m.end();ite++)
{
if(ite->second > maxm) maxm=ite->second;
}
//考虑到会有多个名字含有相同的价值,所以要判断:
//在这些有最大值名字里,谁最先达到最大值;
//方法:再模拟一遍刚才的输入情况;(但是只处理出现最大价值名字的信息)
for(i=0;i<n;i++)
{
if(m[str[i]]==maxm)//筛选出具有最大价值的几个人的信息
{//m用来第一次存储信息,m1 用来第二次筛选时,存储信息;
m1[str[i]]+=temp[i];
if(m1[str[i]]>=maxm)//找到第一个超过最大值的
{
cout<<str[i];
break;//找到后输出,推出,程序结束
}
}
}
return 0;
}
题后总结:1,在这里map容器起到的作用:形成由名字到分数的一个映射,并记录对应名字的分数;
2,不要遇到可以用map容器的题,就全使用map容器,要理解map容器在你的代码中可以起到的作用;
3,在这道题中,map容器起到1中所说的作用,str和temp都起到了暂时存储数据的作用
本题解题思想:线性不定向存储+确定特殊值
线性不定向存储(自己定义的) 最后这些数据会排成一个线行的,但是在存储的过程中,却不是按从左到右的形式存储的数据
对于这样的题目,解决思想是:记录特殊的数据,等所有数据存储完成后,在进行一次处理,筛选出特殊数据;