Removing Columns

来源:互联网 发布:windows 安装xcode教程 编辑:程序博客网 时间:2024/06/14 04:28
C. Removing Columns
time limit per test
 2 seconds
memory limit per test
 256 megabytes
input
 standard input
output
 standard output

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

abcdedfghijk

 

we obtain the table:

acdefghjk

 

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.

Input

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.

Output

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;}


原创粉丝点击