Skip to content

Commit 467a524

Browse files
Add files via upload
1 parent bc240ed commit 467a524

File tree

2 files changed

+104
-0
lines changed

2 files changed

+104
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
Let us make an observation
2+
3+
For every character S[j] that comes after S[i],
4+
If S[j] > S[i], S[j] will have to meet S[i] at some point.
5+
6+
We need to draw an edge between all pairs (i, j) such that
7+
(i < j) and (S[i] > S[j]) and then check for bipartite matching.
8+
9+
We can do this in O(n^2) time.
10+
We will colour a point red if it is uncoloured and then
11+
colour all it's neighbours blue.
12+
13+
If any of it's neighbours is forced to be red, then it is not possible.
14+
15+
-----
16+
17+
int main()
18+
{
19+
int length;
20+
string S;
21+
22+
cin >> length >> S;
23+
24+
vector <int> colour(length, UNCOLOURED);
25+
for(int i = 0; i < length; i++)
26+
{
27+
if(colour[i] == UNCOLOURED)
28+
{
29+
colour[i] = RED;
30+
}
31+
32+
for(int j = i + 1; j < length; j++)
33+
{
34+
if(S[j] < S[i] && colour[j] == UNCOLOURED)
35+
{
36+
colour[j] = other(colour[i]);
37+
38+
continue;
39+
}
40+
41+
if(S[j] < S[i] && colour[i] == colour[j])
42+
{
43+
cout << "NO\n";
44+
45+
return 0;
46+
}
47+
}
48+
}
49+
50+
cout << "YES\n";
51+
for(int i = 0; i < length; i++)
52+
{
53+
cout << colour[i];
54+
}
55+
cout << "\n";
56+
57+
return 0;
58+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
There is a theorem called Dilworth's Theorem. It can be applied here.
2+
3+
We have to count the minimum number of non-decreasing sequences in this array.
4+
5+
This is equal to the length of the longest non-increasing sequence in the array.
6+
7+
We will calculate the length of the longest non-increasing sequence.
8+
9+
As the size of the alphabet is small, we can do it in O(26N) time.
10+
11+
-----
12+
13+
int main()
14+
{
15+
int length;
16+
string S;
17+
cin >> length >> S;
18+
19+
const int NO_OF_ALPHABETS = 26;
20+
vector <int> max_till(NO_OF_ALPHABETS);
21+
vector <int> sequence_no(length, 1);
22+
23+
int no_of_sequences = 0;
24+
for(int i = 0; i < length; i++)
25+
{
26+
for(int alpha = S[i] - 'a' + 1; alpha < NO_OF_ALPHABETS; alpha++)
27+
{
28+
sequence_no[i] = max(sequence_no[i], max_till[alpha] + 1);
29+
}
30+
31+
max_till[S[i] - 'a'] = max(max_till[S[i] - 'a'], sequence_no[i]);
32+
33+
no_of_sequences = max(no_of_sequences, sequence_no[i]);
34+
}
35+
36+
cout << no_of_sequences << "\n";
37+
38+
for(int i = 0; i < length; i++)
39+
{
40+
cout << sequence_no[i] << " ";
41+
}
42+
43+
cout << "\n";
44+
45+
return 0;
46+
}

0 commit comments

Comments
 (0)