AtCoder ABC342 Problem A-D Solutions
Problem A
A slightly trickier warm-up problem.
#include <bits/stdc++.h>
using namespace std;
int main() {
string str;
cin >> str;
unordered_map<char, int> charCount;
for (char c : str) {
charCount[c]++;
}
for (int idx = 0; idx < str.size(); idx++) {
if (charCount[str[idx]] == 1) {
cout << idx + 1 << endl;
return 0;
}
}
return 0;
}
Problem B
Still a straightforward warm-up problem.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> pos(105);
for (int i = 0; i < n; i++) {
int val;
cin >> val;
pos[val - 1] = i;
}
int q_num;
cin >> q_num;
while (q_num--) {
int a, b;
cin >> a >> b;
a--;
b--;
cout << (pos[a] < pos[b] ? a + 1 : b + 1) << endl;
}
return 0;
}
Problem C
A brute-force approach will fail, so we need optimization. Use an array to track character mappings, leveraging the fact that there are only 26 lowercase letters.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> originalToCurrent(26);
for (int i = 0; i < 26; i++) {
originalToCurrent[i] = i;
}
int n;
cin >> n;
string s;
cin >> s;
int q_num;
cin >> q_num;
while (q_num--) {
char from, to;
cin >> from >> to;
int target = from - 'a';
int replacement = to - 'a';
for (int i = 0; i < 26; i++) {
if (originalToCurrent[i] == target) {
originalToCurrent[i] = replacement;
}
}
}
for (char c : s) {
cout << (char)('a' + originalToCurrent[c - 'a']);
}
cout << endl;
return 0;
}
Problem D
A number theory problem. By the Fundamental Theorem of Arithmetic, all exponents of prime factors in a perfect square are even. For each number, we repeatedly divide out squares of primes until no more divsiion is possible. We also need to handle 0 specially, since multiplying it by any number results in a perfect square.
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 200005;
int main() {
int n;
cin >> n;
vector<long long> nums(MAX_N);
unordered_map<long long, int> freq;
long long ans = 0;
int zeroCount = 0;
for (int i = 1; i <= n; i++) {
long long x;
cin >> x;
if (x == 0) {
ans += i - 1 - zeroCount;
zeroCount++;
continue;
}
for (long long j = 2; j * j <= x; j++) {
while (x % (j * j) == 0) {
x /= (j * j);
}
}
ans += freq[x];
freq[x]++;
}
ans += zeroCount * (zeroCount - 1) / 2;
cout << ans << endl;
return 0;
}