Removing Columns - CodeForces 496 C

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

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.

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值