Official

C - One Time Swap Editorial by en_translator


Let \(N\) be the length of \(S\), and \(S_i\) be the \(i\)-th \((1\leq i\leq N)\) character of \(S\).
Moreover, for an integer pair \((i,j)\) such that \(1\leq i<j\leq N\), let \(S(i,j)\) be the string obtained by swapping the \(i\)-th and \(j\)-th characters of \(S\).

Consider the condition where \((i,j)\neq (i',j')\), but \(S(i,j)\) coincides with \(S(i',j')\). If \(S_i\neq S_j\), then \(S\) differs from \(S(i,j)\) only at the \(i\)-th and \(j\)-th characters. Only \(S(i,j)\) satisfies that property, and results from an operation. Thus, if \(S_i\neq S_j\), for no other \((i',j')\), \(S(i,j)\) matches \(S(i',j')\).
On the other hand, if \(S_i=S_j\), then \(S(i,j)\) is identical to \(S\). Thus, it coincides with \(S(i',j')\) for all \(i'\) and \(j'\) such that \(S_{i'}=S_{j'}\).

To summarize, we have the following fact:

  • A string resulting from an operation that does not matches \(S\) corresponds one-to-one to a pair \((i,j)\) such that \(1\leq i<j\leq N\) and \(S_i\neq S_j\).
  • The string \(S\) can result from an operation if and only if \(S\) has repeated occurrences of the same character. That is, if the characters of \(S\) are pairwise distinct, it is impossible; otherwise, it is possible.

The latter can be checked by simply scanning the characters of \(S\). (If the length of \(S\) is \(27\) or greater, then such a pair is always known to exist.)

For the former, we cannot enumerate all pairs \((i,j)\), because it costs \(O(N^2)\) time, which is hard to meet the time limit. However, we can find it by counting the occurrences of each character in \(S\).
Specifically, if \(S\) has \(C_1, C_2,\ldots, C_{26}\) occurrences of a, b, \(\ldots\), z, then there are \(C_1C_2+C_1C_3+\cdots+C_1C_{26}+C_2C_3+\cdots+C_2C_{26}+C_3C_4+\cdots+C_{25}C_{26}\) pairs. It is okay to evaluate it directly, but we can subtract pairs where \(S_i\) and \(S_j\) are the same characters, in order to compute it as \(\frac{1}{2}\{(C_1+C_2+\cdots+C_{26})^2-C_1^2-C_2^2\cdots-C_{26}^2\}=\frac{1}{2}(N^2-C_1^2-C_2^2\cdots-C_{26}^2)\).

Anyway, the problem can be solved in a total of \(O(N)\) time, which is fast enough.
Hence, the problem has been solved.

Sample code in C++:

#include <bits/stdc++.h>

using namespace std;

int main() {
	long long n,ans=0;
	vector<long long>cnt(26);
	bool same=false;
	string s;

	cin>>s;
	n=s.size();
	for(int i=0;i<n;i++){
		cnt[((int)(s[i]-'a'))]++;
	}
	ans=n*n;
	for(int i=0;i<26;i++){
		ans-=cnt[i]*cnt[i];
		if(cnt[i]>1)same=true;
	}
	ans/=2;
	if(same)ans++;
	cout<<ans<<endl;

	return 0;
}

posted:
last update: