// C# program for the above approach
using System;
class GFG {
// Function to preprocess the cost of
// converting the first j character to
// each sequence prefix[i]
static void preprocess(string s, string t,
int[, ] prefix, int n, int i)
{
// Initialize DP array
prefix[i, 0] = 0;
if (s[0] != t[0])
prefix[i, 0] = 1;
for (int j = 1; j < n; j++) {
// prefix[i][j] defines minimum
// operations to transform first j
// characters of s into sequence i
int count = 0;
if (s[j] != t[j % 3])
count++;
prefix[i, j] = prefix[i, j - 1] + count;
}
return;
}
// Function to find the minimum number of
// changes required to make each substring
// between [L, R] non-palindromic
static void minChangesNonPalindrome(string str, int N,
int Q,
int[, ] queries)
{
// Initialize the DP array
int[, ] prefix = new int[6, 100005];
// Initialize the 6 different patterns
// that can be formed to make substrings
// non palindromic
string[] sequences
= { "012", "021", "102", "120", "201", "210" };
for (int i = 0; i < 6; i++) {
// Preprocess the string with
// the ith sequence
preprocess(str, sequences[i], prefix, N, i);
}
// Iterate through queries
for (int i = 0; i < Q; i++) {
int l = queries[i, 0] + 1, r
= queries[i, 1] + 1;
int cost = Int32.MaxValue;
// Find the minimum operations by
// comparing 6 different patterns
// of the substrings
for (int j = 0; j < 6; j++) {
// Find the cost
int count = 0;
if (str[l] != sequences[j][l % 3])
count++;
cost = Math.Min(cost, prefix[j, r]
- prefix[j, l]
+ count);
}
Console.WriteLine(cost);
}
}
static void Main()
{
string S = "0200011011";
int[, ] queries = { { 0, 4 }, { 1, 6 }, { 2, 8 } };
int N = S.Length;
int Q = 3;
minChangesNonPalindrome(S, N, Q, queries);
}
}
// This code is contributed by garg28harsh.