SRM 497(DIVII) 500 PermutationSignature

250分的题,浪费太多时间了,这题就没太多时间看了。这道题初看起来没什么思路,但仔细看看给出的字串还是有规律可循的

 


 

 

Problem Statement

The signature of a permutation is a string that is computed as follows: for each pair of consecutive elements of the permutation, write down the letter 'I' (increasing) if the second element is greater than the first one, otherwise write down the letter 'D' (decreasing).

 

For example, the signature of the permutation {3,1,2,7,4,6,5} is "DIIDID".

 

Your task is to reverse this computation: You are given a string signature containing the signature of a permutation. Find and return the lexicographically smallest permutation with the given signature. If no such permutation exists, return an empty int[] instead.

 

Definition

Class: PermutationSignature

Method: reconstruct

Parameters: string

Returns: int[]

Method signature: int[] reconstruct(string signature)

(be sure your method is public)

 

Notes

- For any positive integer N, a permutation of N elements is a sequence of length N that contains each of the integers 1 through N exactly once.

- To compare two permutations A and B, find the smallest index i such that A[i] and B[i] differ. If A[i] < B[i], we say that A is lexicographically smaller than B, and vice versa.

 

Constraints

- signature will contain between 1 and 50 characters, inclusive.

- Each character in signature will be either 'I' or 'D'.

 

Examples

0)

"IIIII"

Returns: {1, 2, 3, 4, 5, 6 }

 

1)

"DI"

Returns: {2, 1, 3 }

There are two permutations with this signature: {3,1,2} and {2,1,3}. You must return the lexicographically smaller one.

 

2) 

"IIIID"

Returns: {1, 2, 3, 4, 6, 5 }

 

3)

"DIIDID"

Returns: {2, 1, 3, 5, 4, 7, 6 }

 


分析

给一个string signature,signature的每个元素为‘I’或‘D’,让你构造出字典序最小的排列p[],满足sign[i]为‘I’表示p[i] < p[i + 1],sign[i]为'D'表示p[i] > p[i + 1]。

 

算法1

依次处理每个a[0 ~ n],有如下两种情况:

1)当signature[i] == 'I'时,有a[i + 1] = i + 2

2)当signature[i] == 'D'时,就把a最后一段递减数列全部增加1后再让a[i + 1] = a[i] - 1

signature= "IDDIID"

p的变化过程是这样的:

1

12

132

1432(把32都增加1变为43,再添加一个2)

14325

143256

1432576(把6增加1变为7,再添加一个6)

这样每一步都能保证是当前字典序最小的排列,所以最终答案也是字典序最小的了。

 

 

参考:http://www.cnblogs.com/zbwmqlw/archive/2011/02/11/1951251.html

 

算法2

很巧妙的算法,从1开始递增顺序依次填数

 

参考:chokudai的代码

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值