You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table
abcd edfg hijk
we obtain the table:
acd efg hjk
A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
The first line contains two integers — n and m (1 ≤ n, m ≤ 100).
Next n lines contain m small English letters each — the characters of the table.
Print a single number — the minimum number of columns that you need to remove in order to make the table good.
1 10 codeforces
0
4 4 case care test code
2
5 4 code forc esco defo rces
4
In the first sample the table is already good.
In the second sample you may remove the first and third column.
In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).
Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.
这题的突破口在于用一个bool数组来存储当前字符串和后面一个字符串是否需要进行后续的比较,而是否需要比较取决于之前的比较是否能够判断出字符串的大小。
/********************************/
/*Problem: codeforces496C */
/*User: shinelin */
/*Memory: 200K */
/*Time: 31MS */
/*Language: GNU C++ */
/********************************/
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <cstring>
#include <string>
#include <list>
#include <map>
#include <queue>
#include <deque>
#include <stack>
#include <vector>
#include <set>
#include <algorithm>
#include <cmath>
using namespace std;
#define INF 0x7fffffff
#define LL long long
string str[105];
bool cmp[105];
int cnt = 0;
int main()
{
int n, m;
memset(cmp, false, sizeof(cmp));
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i ++)
{
cin >> str[i];
}
for (int k = 0; k < m; k ++)
{
int i;
for (i = 1; i < n; i ++)
{
if(!cmp[i] && str[i][k] > str[i+1][k])
{
cnt ++;
break;
}
}
if(i == n)
{
for (i = 1; i < n; i ++)
{
if(cmp[i]) continue;
if(str[i][k] < str[i+1][k])
{
cmp[i] = true;
}
}
cmp[i] = true; //最后一个字符串不需要和下一个字符串比较。
}
}
cout << cnt << endl;
return 0;
}