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 a
is a substring of string b if it is possible to choose several consecutive letters in b in such a way that they form a. 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".
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
char a[110][110];
struct node
{
int len,id;
}s[110];
bool cmp(node a,node b)
{
return a.len<b.len;
}
int ok(int x,int y)
{
int n,m,j,i,f;
n = strlen(a[x]);
m = strlen(a[y]);
for(i=0;i<=m-n;i++)
{
f = 1;
if(a[x][0] == a[y][i])
{
for(j=0;j<n;j++)
{
if(a[x][j] != a[y][i+j])
{
f = 0;
break;
}
}
if(f) return 0;
}
}
return 1;
}
int main()
{
int n,i,j,m,l1,l2;
cin>>n;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%s",a[i]);
s[i].len = strlen(a[i]);
s[i].id = i;
}
sort(s,s+n,cmp);
int f=0;
for(i=1;i<n;i++)
{
l1 = s[i-1].len;
l2 = s[i].len;
if(l2 > l1)
{
if(ok(s[i-1].id,s[i].id))
{
f=1;
break;
}
}
else if(l1 == l2)
{
if(strcmp(a[s[i-1].id],a[s[i].id]) != 0)
{
f=1;
break;
}
}
if(f) break;
}
if(f) printf("NO\n");
else
{
printf("YES\n");
for(i=0;i<n;i++)
{
printf("%s\n",a[s[i].id]);
}
}
return 0;
}
Input
The first line contains an integer n
(1≤n≤100) — the number of strings.
The next n
lines contain the given strings. The number of letters in each string is from 1 to 100, inclusive. Each string consists of lowercase English letters.
Some strings might be equal.
OutputIf it is impossible to reorder n
given strings in required order, print "NO" (without quotes).
Otherwise print "YES" (without quotes) and n
given strings in required order.
Examples5 a aba abacaba ba aba
YES a ba aba aba abacaba
5 a abacaba ba aba abab
NO
3 qwerty qwerty qwerty
YES qwerty qwerty qwerty
In the second example you cannot reorder the strings because the string "abab" is not a substring of the string "abacaba".
本文探讨了一个字符串重组的问题,即如何重新排列一系列字符串,使得每个字符串都是其前一个字符串的子串。文章提供了一段C++代码实现,展示了如何通过比较字符串长度和子串关系来判断是否可以完成重组。
457

被折叠的 条评论
为什么被折叠?



