XM24. 找“异数”
描述
定义:数值序列中包含2~16进制整数,如果序列中有一个数,与序列中其他任何一个数大小都不相等,则这个数叫做“异数”。请找出给定数值序列中所有的“异数”.输入描述
输入数值序列i行(0<i),每一行分别是进制和数值,以“#”分割。如:n#m, n是整数,代表n进制(1<n<17),m是n进制下的数值.输出描述
输出j行(0<j<=i),每一行都是输入序列的“异数”。要求:示例1
输入:
10#15 4#32 4#33 8#17 END
输出:
4#32
C++ 解法, 执行用时: 57ms, 内存消耗: 12160KB, 提交时间: 2020-12-21
#include <bits/stdc++.h> using namespace std; const int BUFSIZE = 512; unordered_map<int, int> m; struct Node { string a; int val; Node(char *s): a(s){} }; int process(int r, const char *s) { int res = 0; for (int i = 0; i < strlen(s); ++i) { if (s[i] >= '0' && s[i] <= '9') res = res * r + s[i] - '0'; else res = res * r + s[i] - 'A' + 10; } return res; } int main() { char a[BUFSIZE]; vector<Node> v; while (1) { scanf("%s", a); if (!strcmp(a, "END")) break; Node node(a); char *x, *y; x = strtok(a, "#"); y = strtok(NULL, "#"); int p = process(atoi(x), y); node.val = p; v.push_back(node); m[p]++; } int cnt = 0; for (auto &c : v) { if (m[c.val] == 1) {printf("%s\n", c.a.data()); cnt++;} } if (!cnt) printf("None\n"); return 0; }
C++ 解法, 执行用时: 58ms, 内存消耗: 10640KB, 提交时间: 2020-10-29
#include <bits/stdc++.h> using namespace std; const int BUFSIZE = 512; unordered_map<int, int> m; struct Node { string a; int val; Node(char *s): a(s){} }; int process(int r, const char *s) { int res = 0; for (int i = 0; i < strlen(s); ++i) { if (s[i] >= '0' && s[i] <= '9') res = res * r + s[i] - '0'; else res = res * r + s[i] - 'A' + 10; } return res; } int main() { char a[BUFSIZE]; vector<Node> v; while (1) { scanf("%s", a); if (!strcmp(a, "END")) break; Node node(a); char *x, *y; x = strtok(a, "#"); y = strtok(NULL, "#"); int p = process(atoi(x), y); node.val = p; v.push_back(node); m[p]++; } int cnt = 0; for (auto &c : v) { if (m[c.val] == 1) {printf("%s\n", c.a.data()); cnt++;} } if (!cnt) printf("None\n"); return 0; }