988B Substrings Sort

B. Substrings Sort
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given nn strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.

String aa is a substring of string bb if it is possible to choose several consecutive letters in bb in such a way that they form aa. For example, string "for" is contained as a substring in strings "codeforces", "for" and "therefore", but is not contained as a substring in strings "four", "fofo" and "rof".

Input

The first line contains an integer nn (1n1001≤n≤100) — the number of strings.

The next nn lines contain the given strings. The number of letters in each string is from 11 to 100100, inclusive. Each string consists of lowercase English letters.

Some strings might be equal.

Output

If it is impossible to reorder nn given strings in required order, print "NO" (without quotes).

Otherwise print "YES" (without quotes) and nn given strings in required order.

Examples
input
Copy
5
a
aba
abacaba
ba
aba
output
Copy
YES
a
ba
aba
aba
abacaba
input
Copy
5
a
abacaba
ba
aba
abab
output
Copy
NO
input
Copy
3
qwerty
qwerty
qwerty
output
Copy
YES
qwerty
qwerty
qwerty
Note

In the second example you cannot reorder the strings because the string "abab" is not a substring of the string "abacaba".


题意:输入n个字符串,按照长度读排序后,如果前面的字符串是后一个的子串,就输出YES,输出排序后的字符串,否则就输出NO。

题解:我能说我昨晚做的时候,别人都是比较字符串长度,我画蛇添足的多了一个字典序,然后一直RE 第四组数据,去掉字典序就ok了...抓狂 按照字符串长度排序后直接用find 函数查找前面一个是不是后面的自子串(后面的串是否包含前一个字符串),是的话就输出YES,输出排序后的,没有就no。如果不懂find函数怎么用,点击传送门:c++ find函数用发总结

c++:

#include<bits/stdc++.h>
using namespace std;
bool cmp(string a, string b)
{
    return a.size()<b.size();
}
int main()
{
    string s[1100];
    int n;
    cin>>n;
    for(int i=0; i<n; i++)
        cin>>s[i];
    sort(s,s+n,cmp);
    for(int i=0; i<n-1; i++)
        if(s[i+1].find(s[i])==s[i+1].npos)
        {
            puts("NO");
            return 0;
        }
    puts("YES");
    for(int i=0; i<n; i++)
        cout<<s[i]<<endl;
    return 0;
}

python:

n=int(input())
s=[]
for i in range(n):
        s.append(input())
s=sorted(s,key=len)
for i in range(n-1):
        if s[i] not in s[i+1]:
              print("NO")
              exit()
print("YES")
for i in s:
      print(i)
        


猜你喜欢

转载自blog.csdn.net/memory_qianxiao/article/details/80547830
今日推荐