zl程序教程

您现在的位置是:首页 >  云平台

当前栏目

【codeforces 777D】Cloud of Hashtags

Cloud of Codeforces
2023-09-14 09:03:48 时间

【题目链接】:http://codeforces.com/contest/777/problem/D

【题意】
让你通过删除字符串的末尾字符的方式;
使得所给的字符串以字典序升序排序;
不能交换字符串之间的位置;

【题解】

/*
    要求字符串的字典序升序排;
    不能交换字符串的位置;
    那就使得
    s[i]<=s[i+1]对i∈[1..n-1]都成立就好;
    (这里的<=指的是字典序的小于等于);
    从最后一个字符串开始;
    逆序处理字符串1..n-1;
    对比字符串s[i]和s[i+1]的所有字符;
    对比的时候len = min(s[i].size(),s[i+1].size());
    找到第一个字符不一样的位置pos;
    如果找到了这样一个pos;
    记录它
    if (s[i][pos]<s[i+1][pos])
        则这个字符串出现在这里是合法的;
    符合s[i]<=s[i+1]
    if (s[i][pos]>s[i+1][pos])
        则把s[i]从pos开始全部删掉;
    然后处理下一个;

    当然,如果pos没有找到的话,就比较s[i].size()和s[i+1].size();
    如果s[i].size()<=s[i+1].size();则合法
    否则从s[i].size()+1开始把s[i]从s[i].size()+1一直到结束全部删掉
    (可以不用真的删掉吧。写一个to[n];
    表示每个字符串输出的时候要一直输出到哪个地方.
*/


【完整代码】

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define rei(x) scanf("%d",&x)
#define rel(x) scanf("%lld",&x)

typedef pair<int, int> pii;
typedef pair<LL, LL> pll;

const int dx[9] = { 0,1,-1,0,0,-1,-1,1,1 };
const int dy[9] = { 0,0,0,-1,1,-1,1,-1,1 };
const double pi = acos(-1.0);
const int N = 5e5 + 100;

string s[N];
int n;
int to[N];
bool bo[N];

int main()
{
    //读入优化??
    //freopen("D:\\rush.txt", "r", stdin);
    rei(n);
    rep1(i, 1, n)
        cin >> s[i];
    int len = s[n].size();
    len--;
    to[n] = len;
    rep2(i, n - 1, 1)
    {
        int len = min(to[i + 1], int(s[i].size())-1);
        int pos = -1;
        rep1(j,1,len)
            if (s[i][j] != s[i + 1][j])
            {
                pos = j;
                break;
            }
        if (pos != -1)
        {
            if (s[i][pos] < s[i + 1][pos])
            {
                to[i] = int(s[i].size())-1;
                continue;
            }
            if (s[i][pos] > s[i + 1][pos])
            {
                to[i] = pos - 1;
                continue;
            }
        }
        if (int(s[i].size()) <= to[i + 1])
        {
            to[i] = int(s[i].size())-1;
            continue;
        }
        to[i] = to[i + 1];
    }
    rep1(i, 1, n)
    {
        putchar('#');
        rep1(j, 1, to[i])
            putchar(s[i][j]);
        puts("");
    }
    return 0;
}