SRM 207 Div II Level Two: RegularSeason,字符串操作(sstream),多关键字排序( 比较函数 )

题目来源: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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值