题目来源:http://community.topcoder.com/stat?c=problem_statement&pm=2866&rd=5853
主要是要对字符串的操作要熟悉,熟练使用 sstream 流可以大大简化操作,如这个题目,如果不用sstream 流的话,用 sscanf 函数非常麻烦,因为输入的数据中数字的个数不是一样的,还有一个问题就是多关键字的排序,用 sort 函数时要自己写比较函数。
另外那个得到实现四则运算的方法也很巧妙,我刚始用的方法比较麻烦,这种方法看别人代码知道的。
代码如下:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;
class RegularSeason
{
public:
vector <string> finalStandings(vector <string> teams, int rounds);
};
struct Team {
int wins;
string name;
};
/* 比较函数 */
bool cmp (const Team &a, const Team &b)
{
if ( a.wins != b.wins ) {
return a.wins > b.wins; /* 按 wins */
} else {
return a.name < b.name; /* 按 name */
}
}
//bool operator< (const Team &a, const Team &b)
//{
// if ( a.wins != b.wins ) {
// return a.wins > b.wins; /* 按 wins */
// } else {
// return a.name < b.name; /* 按 name */
// }
//};
vector <string> RegularSeason::finalStandings(vector <string> teams, int rounds)
{
int num = teams.size();
int prob;
vector <Team> vt(num);
vector <string> ans;
for (int i = 0; i < num; i++) {
vt[i].wins = 0;
}
for (int i = 0; i < num; i++) {
istringstream iss(teams[i]);
iss >> vt[i].name;
for (int j = 0; j < num; j++) {
iss >> prob; /* 得到羸的可能值 */
if (i != j) { /* 更新期望值 */
vt[j].wins += rounds * (100 - prob);
vt[i].wins += rounds * prob;
}
}
}
sort(vt.begin(), vt.end(), cmp);
for (int i = 0; i < num; i++) {
ostringstream oss;
int iwins = vt[i].wins;
string teamname = vt[i].name;
/* 四舍5入约分 */
iwins = (iwins + 50) / 100;
oss << teamname << " " << iwins;
ans.push_back(oss.str());
}
return ans;
}