1056 组合数的和——15分

给定N个非0的个位数字,用其中任意2个数字都可以组合成1个2位的数字。要求所有可能组合出来的2位数字的和。例如给定2、5、8,则可以组合出:25、28、52、58、82、85,它们的和为330。

输入格式:

输入在一行中先给出N(1<N<10),随后是N个不同的非0个位数字。数字间以空格分隔。

输出格式:

输出所有可能组合出来的2位数字的和。

输入样例:

3 2 8 5

输出样例:

330

| 代码长度限制 | 时间限制 | 内存限制 |
| 16KB | 400ms | 64MB |

代码:

#include<bits/stdtr1c++.h>
using namespace std;
int main() {
	int n; char c; string s;
	set<int> st; //用集合对数字进行去重,防止重复计算
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> c;
		s += c; //将每个数字加入字符串中
	}
	sort(s.begin(), s.end()); //对数字从小到大排列
	int sum = 0;
	do {
		st.insert(stoi(s.substr(0, 2))); //提取前两位,加入集合中
	} while (next_permutation(s.begin(), s.end())); //重新排列
	for (auto x : st) sum += x;
	cout << sum;
	return 0;
}
posted @ 2022-08-14 08:53  Fare-Well  阅读(41)  评论(0)    收藏  举报