P9868

· · 题解

Description

给定 n 个两两不同且长度均为 m 的字符串 w_1,w_2,\cdots,w_n(都由小写字母构成)。

对于每个 1 \le i \le n,问是否可以将字符串们各自的字符重新排序,使得 i 的字典序比其它字符串小。n=1 时,我们约定上述性质是成立的。

Solution

考场上第一眼想到用 sort() 直接对每个字符串内的字符逆序、顺序各求一遍,如果 w_i 的顺序排列小于其它所有字符串的逆序排列就输出 1。

但是直接对字符串暴力比较的时间复杂度为 \mathcal O(nm^2),本地跑出了 4s 的好成绩。然后换成了计数排序,时间复杂度 \mathcal O(nm),还带了一个 26 的常数,本地跑了 1s。

考完后想了想,似乎没必要排序,直接记录最大的字符和最小的字符就行了。

如果 a 表示字符串 A 的最小字符,b 表示字符串 B 的最大字符:

综上:判断字符串 A 是否满足性质,即判断 A 的最小字符是否小于其它所有字符串的最大字符。

时间复杂度 \mathcal O(nm)。

Code

#include <iostream>
using namespace std;
const int N = 3003;
int n, m;
char minn[N], maxx[N];
int read(){
    int x = 0;
    bool tf = 1;
    char a = getchar();
    while(a < '0' || '9' < a) a == '-'? tf = 0: -1, a = getchar();
    while('0' <= a && a <= '9') x = (x << 1) + (x << 3) + (a ^ 48), a = getchar();
    return tf? x: -x;
}
int main(){
    n = read(), m = read();
    for(int i = 1; i <= n; ++ i){
        char a = getchar();
        while(a < 'a' || 'z' < a) a = getchar();
        minn[i] = maxx[i] = a;
        for(int j = 2; j <= m; ++ j){
            a = getchar();
            if(a < minn[i]) minn[i] = a;
            if(a > maxx[i]) maxx[i] = a;
        }
    }
    for(int i = 1; i <= n; ++ i){
        bool tf = 1;
        for(int j = 1; j <= n; ++ j)
            if(i != j && minn[i] >= maxx[j]){
                tf = 0;
                break;
            }
        putchar(tf? '1': '0');
    }
    return 0;
}