Codeforces Problem - 37C - Old Berland Language(DFS|字典树)

C. Old Berland Language
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Berland scientists know that the Old Berland language had exactly n words. Those words had lengths of l1, l2, ..., ln letters. Every word consisted of two letters, 0 and 1. Ancient Berland people spoke quickly and didn’t make pauses between the words, but at the same time they could always understand each other perfectly. It was possible because no word was a prefix of another one. The prefix of a string is considered to be one of its substrings that starts from the initial symbol.

Help the scientists determine whether all the words of the Old Berland language can be reconstructed and if they can, output the words themselves.

Input

The first line contains one integer N (1 ≤ N ≤ 1000) — the number of words in Old Berland language. The second line contains Nspace-separated integers — the lengths of these words. All the lengths are natural numbers not exceeding 1000.

Output

If there’s no such set of words, in the single line output NO. Otherwise, in the first line output YES, and in the next N lines output the words themselves in the order their lengths were given in the input file. If the answer is not unique, output any.

Examples
input
Copy
3
1 2 3
output
YES
0
10
110
input
Copy
3
1 1 1
output
NO

题意:

判断是否存在n个长度分别为Li的仅有01两种字符组成的,并且没有一个字符串是其他字符串的前缀的字符串


思路:

所有前缀不可为其他串,可以利用01字典树,也可以直接dfs搜,每个点只能用两次,第一次加'0'第二次加'1'

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
using namespace std;
const int N = 1e6 + 10;
int n,x,y,z,cnt = 0,k = 0,v[N];
char s[1010];
struct node{
    int len, id;
    char s[1010];
}a[1010];
bool cmp1(node a,node b){
    return a.len<b.len;
}
bool cmp2(node a,node b){
    return a.id<b.id;
}
void dfs(int len,int pos){
    if(k==n) return;
    if(len==a[k].len){
        strcpy(a[k++].s, s);
        return;
    }
    while(v[pos]<2){
        s[len] = '0'+v[pos]++;
        dfs(len+1, ++cnt);
    }
}
int main()
{
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&x);
        a[i].len = x; a[i].id = i;
    }
    sort(a,a+n,cmp1);
    dfs(0, 0);
    sort(a,a+n,cmp2);
    if(k<n) printf("NO\n");
    else{
        printf("YES\n");
        for(int i=0;i<n;i++) puts(a[i].s);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/w326159487/article/details/79750655