Topic:
A string of beads (m) connected to the end, having N colors (n<=10),
Design an algorithm that takes out one paragraph and requires all the colors in N, and minimizes the length.
And analyze the time complexity and space complexity.
Analysis:
Use an extra array to store the color count: colors[n], and define a number of colors to traverse int cn=0;
Use array a[m] to represent the beads at the end of the link.
Traversal array A, statistics the corresponding color, if equal to the number of colors equals N, record start position I, and end position J, get the length of the string j-i+1, if the length of the string is minimal, then output i,j.
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
The complexity of Time is: O (n),
Space complexity: O (1*n)
Specifically implemented as follows:
#include <iostream> #include <string.h> using namespace std; M string a:0,1,..., m-1//n colors:0,1,..., N-1//#define M #define N 3 int findmin (int a[m], int colors[n],
int& begin, int& end) {begin = 0;
end =-1;
int i = 0;
int j = 0;
int cn = 0;
int minlen = m;
Colors[a[0]] + +;
CN + +;
while (I < m) {//memset (colors, 0, n*sizeof (int));
j = i;
bool BL = false;
while (j== 0 | | | J!= i) {if (BL) {if (colors[a[j)] = = 0)
CN + +;
COLORS[A[J]] + +;
BL = true;
if (cn = = N) {int len = J-i +1;
if (Len < 0) Len + = m;
if (Len < Minlen) {begin = i; End = J
Minlen = j-i + 1;
} break;
} j = (j+1)%m;
} if (i = = J && Minlen = m) break;
Colors[a[i]] = Colors[a[i]]-1;
if (colors[a[i]] = = 0) cn--;
i++;
return Minlen;
int main () {int a[m] = {2,1,0,1,1,2,1,0,1,1};
int C[n] = {0,0,0};
int begin= 0, end = 0;
int minlen = Findmin (A, C, begin, end);
int i = 0;
cout << "string:";
while (I < m) {cout << a[i] << ",";
i + +;
} cout << "Minlen:" << minlen << Endl;
cout << begin << "," << end << Endl; }
The output is as follows:
string:2,1,0,1,1,2,1,0,1,1, Minlen:3
0,2
Author: csdn Blog hhh3h