using
System;
using
System.Collections.Generic;
public
class
AnagramSwaps {
public
static
bool
CheckIsAnagram(
int
[] charCountS,
int
[] charCountS1)
{
for
(
int
i = 0; i < 26; i++) {
if
(charCountS[i] != charCountS1[i]) {
return
false
;
}
}
return
true
;
}
public
static
int
[] GetCharCount(
string
S)
{
int
[] charCount =
new
int
[26];
foreach
(
char
c
in
S) { charCount++; }
return
charCount;
}
public
static
int
Get(
int
[] fenwickTree,
int
index)
{
int
leftShift = 0;
leftShift += fenwickTree[index];
while
(index > 0) {
index -= (-index) & index;
leftShift += fenwickTree[index];
}
return
leftShift;
}
public
static
void
Update(
int
[] fenwickTree,
int
index)
{
while
(index < fenwickTree.Length) {
fenwickTree[index] += 1;
index += (-index) & index;
}
}
public
static
List<
int
>[] GetPositions(
string
S)
{
List<
int
>[] charPositions =
new
List<
int
>[ 26 ];
for
(
int
i = 0; i < 26; i++) {
charPositions[i] =
new
List<
int
>();
}
for
(
int
i = 0; i < S.Length; i++) {
charPositions[S[i] -
'a'
].Add(i);
}
return
charPositions;
}
public
static
int
FindMinMoves(
string
S,
string
S1)
{
int
minMoves = 0;
int
[] fenwickTree =
new
int
[S.Length + 1];
List<
int
>[] charPositions =
new
List<
int
>[ 26 ];
for
(
int
i = 0; i < 26; i++) {
charPositions[i] =
new
List<
int
>();
}
int
j = 0;
foreach
(
char
c
in
S1)
{
charPositions.Add(j);
j++;
}
for
(
int
i = S.Length - 1; i >= 0; i--) {
List<
int
> temp = charPositions[S[i] -
'a'
];
int
size = temp.Count - 1;
int
index = temp[size] + 1;
charPositions[S[i] -
'a'
].RemoveAt(size);
int
leftShift = Get(fenwickTree, index);
Update(fenwickTree, index);
index -= leftShift;
minMoves += Math.Abs(i - index + 1);
}
return
minMoves;
}
public
static
string
GetBestString(
string
S,
string
[]
group
)
{
bool
isAnagram =
false
;
string
bestString =
""
;
int
minMoves =
int
.MaxValue;
int
[] charCountS = GetCharCount(S);
foreach
(
string
S1
in
group
)
{
int
[] charCountS1 = GetCharCount(S1);
bool
anagram
= CheckIsAnagram(charCountS, charCountS1);
if
(!anagram)
continue
;
isAnagram =
true
;
int
moves = FindMinMoves(S, S1);
if
(moves < minMoves) {
minMoves = moves;
bestString = S1;
}
}
return
isAnagram ? bestString :
"-1"
;
}
static
void
Main(
string
[] args)
{
string
S =
"abcdac"
;
string
[] arr = {
"cbdaca"
,
"abcacd"
,
"abcdef"
};
string
bestString = GetBestString(S, arr);
Console.WriteLine(bestString);
}
}