作者felixgwu (哈哈哈之王)
看板b99902HW
标题[讨论] testgirl第47题,请强者帮忙解惑!
时间Sat Nov 20 15:16:07 2010
如题,testgirl的第47题,无论小弟我如何尝试,
执行时间仍然会爆表
请问强者们,要怎麽做才能减少我的运算时间?
麻烦强者赐教
底下是题目和我的程式码
题目:
Practice 04 (recursive function)
Given a integer N, print out the N! combination composed of first N upper letters.
The output answers should be in lexical order.
Hint: you may need arrays to assist you in the recursive process.
Input format:
One integer per line. The integers will range from 1 to 10.
Output format:
Print out all the combinations, one combination per line.
Between every case, you should print a line cotaining only '.' .
Example:
Input:
1
2
3
Output:
A
.
AB
BA
.
ABC
ACB
BAC
BCA
CAB
CBA
然後这是我的程式码:
#include<stdio.h>
void re(int l,int n,int s[],int p[]);
int main()
{
int i,j,k,b=0;
int s[10],p[10];
int n,l;
while(scanf("%d",&l)!=EOF)
{
if(b==0)
b=1;
else
printf(".\n");
for(i=0;i<l;i++)
s[i]=i;
re(l,0,s,p);
}
return 0;
}
void re(int l,int n,int s[],int p[])
{
int i,j,h;
for(i=0;i<l;i++)
{
if(s[i]==-1)
continue;
p[n]=s[i];
s[i]=-1;
re(l,n+1,s,p);
s[i]=p[n];
}
if(n==l)
{
for(i=0;i<l;i++)
printf("%c",'A'+p[i]);
printf("\n");
}
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.112.242.229
1F:推 suhorng:路人路过... 把 printf("%c", 'A'+p[i]); 换成 putchar( 11/20 21:42
2F:→ suhorng:'A'+p[i]); 应该就可以了 :P 这题最花时间的是 output 11/20 21:42
3F:→ xluds24805:l 和 1 看起来好像@@ 11/20 21:44
4F:→ felixgwu:非常感谢suhorng的回答,上了宝贵的一课。 11/20 22:24
5F:→ xluds24805:为什麽换成putchar就比较不会花时间丫~_~? 11/20 23:27
6F:推 innocentguy:suhrong耶........... 11/21 23:17