Codeforces Beta Round #37 C. Old Berland Language

本文提供了一道CodeForces竞赛题目37C的详细解答过程,该题要求构造多个由‘0’和‘1’组成的字符串,并确保任一字符串不是其他字符串的前缀。通过深度优先搜索算法(DFS)实现了解题思路,同时给出了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 题目链接:http://codeforces.com/contest/37/problem/C
  • 题意:让你构造n个由‘0’和‘1’构成字符串,其长度分别为l1, l2, l3,…ln. 要使任意一个串不为任意另一个串的 开头子串。
  • 思路:手动模拟一下可以知道:

    1. 当n==1, l[1]==1时,s[1]==“0”或“1”
    2. 当n==2 ,l[1]==1, l[2]==1时, s[1]==”0”, s[2]==”1”
    3. 当n==3, l[1]==1, l[2]==1, l[3]==1时,无法构建

即当n>=3时,若l[1]==1,s[1]==”0”, 则l[2]不能==1, 而是应该在“1”的基础上再加上一个“0”或“1”,即变为“10”或“11”。以此类推:每个长度下只能保留一个字符串,另一个要拿去构建下一个字符串,知道n-1个字符串时,才允许吧第n个字符串放在与n-1同一个长度层
这里写图片描述

  • 算法:DFS

#include <bits/stdc++.h>
#define pi acos(-1)
using namespace std;
typedef long long LL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const LL ll_INF = 0x3f3f3f3f3f3f3f3f;//4e18 ~= 2^62
const int N =1000 + 10;
const LL mod = 1e9+7;

int n, tot=0, flag=0;

struct S
{
    int len, ind;
    string s;
}p[N];


bool cmp(const S a, const S b)
{
    return a.len<b.len;
}


bool cmp2(const S a, const S b)
{
    return a.ind<b.ind;
}


void DFS(int x, string s)
{
    if(x==p[tot].len){
        p[tot++].s = s;
        if(tot==n) flag=1;
        return;
    }
    DFS(x+1, s+'0');
    if(tot==n) return;
    DFS(x+1, s+'1');
}

int main()
{
    scanf("%d", &n);
    for(int i=0; i<n; i++){
        scanf("%d", &p[i].len);
        p[i].ind=i;
        p[i].s="";
    }
    sort(p, p+n, cmp);
    DFS(0, "");
    if(flag==0) { printf("NO\n"); return 0; }
    sort(p, p+n, cmp2);
    puts("YES");
    for(int i=0; i<n; i++){
        cout<<p[i].s<<endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值