列表

详情


NC54479. Jokewithpermutation

描述

Joey had saved a permutation of integers from 1 to n in a text file. All the numbers were written as decimal 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!

输入描述

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.

输出描述

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.

示例1

输入:

4111109876532

输出:

4 1 11 10 9 8 7 6 5 3 2

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++11(clang++ 3.9) 解法, 执行用时: 7ms, 内存消耗: 500K, 提交时间: 2020-10-06 10:23:10

#include<bits/stdc++.h>
using namespace std;
char p[1100];
int n,k=0;
bool vis[55];
int a[100];
void dfs(int x,int y){
    if(x==n&&y==strlen(p)){
        for(int i=0;i<n;i++) 
            printf("%d ",a[i]);
                   k=1;
    }
    if(x>n||k==1||y>strlen(p))return;
    int r=0;
    while(1){
        r=r*10+p[y]-'0';y++;
        if(r>n||y>strlen(p)) break;
        if(vis[r]==1) continue;
        vis[r]=1;a[x]=r;
        dfs(x+1,y);
        if(k) return;
        vis[r]=0;
    }
}
int main(){
    scanf("%s",p);
    if(strlen(p)<=9) n=strlen(p);
    else n=9+(strlen(p)-9)/2;
    dfs(0,0);
}

C++14(g++5.4) 解法, 执行用时: 10ms, 内存消耗: 416K, 提交时间: 2020-10-14 19:09:49

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char s[100];
int a[100],b[100];
int l;
bool f[100];
void dfs(int x,int y,int k)
{
	if (k>l)
	{
		for(int i=1;i<=l;i++)
			printf("%d ",b[i]);
		exit(0);
	}
	if (y>0&&y<=l&&!f[y])
	{
		f[y]=true;
		b[k]=y;
		dfs(x+1,a[x+1],k+1);
		f[y]=false;
	}
	if (x<strlen(s+1))
	{ 
		int o=y*10+a[x+1];
		if (o<=l&&!f[o])
			dfs(x+1,o,k);
	} 
}
int main()
{
	scanf("%s",s+1);
	l=strlen(s+1);
	for(int i=1;i<=l;i++) a[i]=s[i]-'0';
	if (l>9) l=(l-9)/2+9;
	dfs(1,a[1],1);
	return 0;
}

上一题