Problems and their tricks
For number of characters of each character in string
⏩ char 'c' - A'
vector<int> v(26); // "26" alphabets in English Lnaguage
for (char c : str)
{
v.at(c - 'A')++;
// if "c" = 'A' then (c - 'A') => ['65' - '65' = "0"] ; as 'A' ASCII value is "65" and (c = 'A' = 65 also)
// if "c" = 'A' then (c - 'A') => ['68' - '65' = "3"] ; as 'A' ASCII value is "65" and c = 'D' = 68
}
For converting the index created above
as char
⏩ indexNo. "i" + 'A'
dq.emplace_back(i + 'A');
// index is the IndexNo. here
// If the IndexNo. "i" is 3 then then ("3" + "65") = ("68") as 'A' ASCII value is "65" ; hence 'D' = 68 ,,
// So "(i +'A') = 68"
caution
using both the above tricks:
CSES Problem: Palindrome Reader :~ Converting/Checking a String to Palindrome
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define endl "\n"
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
string str;
cin >> str;
vector<int> v(26);
deque<char> dq;
for (auto el : str)
{
v.at(el - 'A')++;
}
int count = 0;
for (int i = 0; i < v.size(); i++)
{
if (v.at(i) % 2 != 0)
{
++count;
}
if (count > 1)
{
cout << "NO SOLUTION" << endl;
return 0;
}
}
// making the palindrome
// odd first added
for (int i = 0; i < v.size(); i++)
{
if (v.at(i) % 2 != 0)
{
for (int j = 0; j < v.at(i); j++)
{
dq.emplace_back(i + 'A');
}
}
}
// for even
for (int i = 0; i < v.size(); i++)
{
if (!(v.at(i) % 2))
{
// emplace_back
for (int j = 0; j < (v.at(i) / 2); j++)
{
dq.emplace_back(i + 'A');
}
// emplace_front
for (int j = 0; j < v.at(i) / 2; j++)
{
dq.emplace_front(i + 'A');
}
}
}
string ans;
for (auto el : dq)
{
ans.push_back(el);
}
cout << ans << endl;
return 0;
}
cycle type problems inside a loop
for(int i=0;i<100;++i) {
pour(i%N, (i+1)%N); // Pour milk from one bucket to the next
/* 1 ⇢ 2 ⇢ 3 ⇢ 1 */
// and then this gets repeated again "0%3 1%3 2%3 3%3[0 here] 4%3 5%3 6%3[0 here] ...."
}
solution using cycle inside `loop` ⇢⇢ the question
#include <bits/stdc++.h>
using namespace std;
vector<int> cap(3);
vector<int> am(3);
void sol(int a, int b)
{
int x = min(cap.at(b) - am.at(b), am.at(a));
am.at(a) -= x;
am.at(b) += x;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int tmp;
for (int i = 0; i < 3; i++)
{
cin >> tmp;
cap.at(i) = tmp;
cin >> tmp;
am.at(i) = tmp;
}
for (int i = 0; i < 100; i++)
{
sol(i % 3, (i + 1) % 3);
}
for (auto el : am)
{
cout << el << endl;
}
return 0;
}