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.
题意:
题意的话比较简单,就是有n*m的字符串矩阵,可以删除任意列的字符,要求删除完后整个矩阵从上到下的每一行要按字典序排列;
思路:
按照字符串矩阵建立一个dp矩阵,可以从第二行开始,每一行都和上一行进行比较,如果不符合字典序的话就做下标记。然后从第二行开始遍历,如果遇到这一行的字符小于上一行的就break;如果遇到这一行的字符和上一行的字符相同的就继续循环,如果遇到有标记的就在这一列下标记,说明这一列已经被删除了,下一次遇到有标记的就跳过。
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MAX_N = 2e2+9;
char vec[MAX_N][MAX_N];
int res[MAX_N][MAX_N];
int out[MAX_N];
int main()
{
int N,M,T;
while(cin>>N>>M)
{
memset(res,0,sizeof(res));
memset(out,0,sizeof(out));
for(int i=0; i<N; i++)
{
scanf("%s",&vec[i]);
}
if(N==1)
{
cout<<"0"<<endl;
continue;
}
for(int i=1; i<N; i++)
{
for(int j=0; j<M; j++)
{
if(vec[i][j] < vec[i-1][j])
{
res[i][j] = 1;
//cout<<i<<"........"<<j<<endl;
}
}
}
while(1)
{
bool update = true;
for(int i=1; i<N; i++)
{
for(int j=0; j<M; j++)
{
if(out[j] == 1) continue;
if(res[i][j])
{
update = false;
out[j] = 1;
//cout<<j<<"!!!!!"<<endl;
}
if(!res[i][j] && vec[i][j] != vec[i-1][j]) break;
}
}
if(update) break;
}
int ans = 0;
for(int i=0; i<M; i++)
{
ans += out[i];
}
cout<<ans<<endl;
}
return 0;
}