Jokewithpermutation Gym - 100553J (bfs)

面对一个由1到n的整数排列字符串,所有空格被移除的难题,本文介绍了一个深度优先搜索算法来复原原始排列。通过在适当位置插入空格,此算法能有效解决由Joey恶作剧引发的问题。

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

Jokewithpermutation

 Gym - 100553J 

 

Joey had saved a permutation of integers from 1 to n in a text file. All the numbers were written asdecimal numbers without leading spaces.

Then Joe made a practical joke on her: he removed all the spaces in the file.

Help Joey to restore the original permutation after the Joe’s joke!

 

Input

The input file contains a single line with a single string — the Joey’s permutation without spaces.

The Joey’s permutation had at least 1 and at most 50 numbers.

 

Output

Write a line to the output file with the restored permutation. Don’t forget the spaces!

If there are several possible original permutations, write any one of them.

 

Sample input and output

4111109876532                                   

4 1 11 10 9 8 7 6 5 3

https://vjudge.net/contest/328613#problem/J

题意:n个数(n<=50)写在一行,之间的空格被去掉,要求复原

 

dfs找合适的情况,每次在一个数后面加空格或在两个数后面加空格

#include <bits/stdc++.h>

char s[250];
int len,num;
int  dfs(int n,int flag[51])
{
    if(n == -1)
        return 1;
    int numm = s[n]-'0';
    if(s[n]!='0'&&numm <= num&&!flag[numm])
    {
        flag[numm] = 1;
        if(dfs(n-1,flag))
        {
            if(n == 0)
                printf("%c",s[n]);
            else
                printf(" %c",s[n]);
            return 1;
        }
        flag[numm] = 0;

    }

    if(n >=1)
    {
        numm = (s[n-1]-'0')*10+s[n]-'0';
        if(s[n-1]!='0'&&numm <= num&&!flag[numm])
        {
            flag[numm] = 1;
            if(dfs(n-2,flag))
            {
                if(n-1==0)
                    printf("%c%c",s[n-1],s[n]);
                else
                    printf(" %c%c",s[n-1],s[n]);
                return 1;
            }
            flag[numm] = 0;
        }

    }
    return 0;

}
void init()
{
    freopen("joke.in", "r", stdin);
    freopen("joke.out", "w", stdout);
}

int main()
{
    //init();
    int flag[56];
    scanf("%s",s);
    len = strlen(s);
    if(len <= 9)
        num = 9;
    else
    {
        num = (len-9)/2+9;
    }
    memset(flag,0,sizeof(flag));
    dfs(len-1,flag);
    printf("\n");

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值