切换到宽版
  • 4150阅读
  • 0回复

救救我吧  帮忙优化程序 [复制链接]

上一主题 下一主题
离线王智誉
 
只看楼主 倒序阅读 0 发表于: 2009-08-01
排列的序号
Time Limit:1000MS  Memory Limit:65536K
Total Submit:28 Accepted:6
Description
如果我们将n个元素的全排列象字符串一样按字典排序的话,则其中的每一个排列都对应唯一的一个序号。如n=4时,排列1 2 3 4 的序号为0,而排列 4 3 2 1的序号为23。要求在给定n(n为自然数,由键盘输入)后,编程实现:输入一个1到n的排列,输出其序号。

Input
两行数
第一行:n(排列中数的个数) (n<=10)
第二行:某个排列(空格隔开)

Output
一个整数(表示这个排列的序号)(序号在长整范围内)
Sample Input

Sample Output

[pre]23[/pre][pre]我的程序:[/pre][pre][pre]var m,n,i,j,x,k:longint;    a,b:array[1..20] of integer;procedure print;begin for i:=1 to n-1 do  for j:=i to n do  if (i<>j) and (a=a[j]) then exit; inc(k); for i:=1 to n do  if a<>b then exit; writeln(k); haltend;procedure change(ws:integer); begin  if ws=n then begin           repeat            inc(a[ws]);            if (a[ws]<m-1) and (a[ws]=a[ws-1]) then inc(a[ws]);            print;           until a[ws]>=m; end          else           repeat            inc(a[ws]);            if (ws<>1) and (a[ws]<m-1) and (a[ws]=a[ws-1]) then inc(a[ws]);            a[ws+1]:=0;            change(ws+1);           until a[ws]>=m; end;begin k:=-1; readln(n); for i:=1 to n do  read(b); m:=n; for i:=1 to n do  a:=i-1; change(1);end.[/pre]




[pre]
第n个排列
Time Limit:1000MS  Memory Limit:65536K
Total Submit:9 Accepted:5
Description
如果我们将n个元素的全排列象字符串一样按字典排序的话,则其中的每一个排列都对应唯一的一个序号。如n=4时,排列1 2 3 4 的序号为0,而排列 4 3 2 1的序号为23。要求在给定n(n为自然数,由键盘输入)后,编程实现:输入一个排列的序号,输出相应的排列。

Input
两行整数
第一行 n(排列中数的个数)(n<=10)
第二行 一个整数(长整范围内一个数)

Output
一行整数(表示所求的排列,每个数之间一个空格隔开)
Sample Input

Sample Output

[pre]1 2 3 4[/pre]

[pre]我的程序:[/pre][pre][pre]var m,n,i,j,x,k:longint;    a:array[1..20] of integer;procedure print;begin for i:=1 to n-1 do  for j:=i to n do  if (i<>j) and (a=a[j]) then exit; inc(k); if k<>x then exit; for j:=1 to n-1 do  write(a[j],'':1); writeln(a[n]); haltend;procedure change(ws:integer); begin  if ws=n then begin           repeat            inc(a[ws]);            print;           until a[ws]>=m; end          else           repeat            inc(a[ws]);            a[ws+1]:=0;            change(ws+1);           until a[ws]>=m; end;begin k:=-1; readln(n); readln(x); m:=n; for i:=1 to n do  a:=i-1; change(1);end.[/pre][pre] [/pre]


[pre]我自己测试对的 但在测试平台上超时[/pre]
[pre]帮忙优化一下[/pre][/pre]
[pre]40[/pre][/pre][/pre]
[pre]44 3 2 1[/pre]
快速回复
限100 字节
 
上一个 下一个