uva639 - Don't Get Rooked

对于这个题,开始弄了个跑20ms的代码,一个小时的优化后,跑了12ms。。。。
思路不难,就是把问题分成一步步的。
每一步弄成个递归就行了。先贴一下20ms 的代码/

代码如下:

#include <cstdio>
char f[5][5];
int  n, max;
int is_caninset(int c, int l)
{
    if(f[c][l]=='X'||f[c][l]=='/'||f[c][l]=='o')return 0;
    for(int i = l+1; i < n; i++)
    if(f[c][i]=='X') break;
    else if(f[c][i]=='/') return 0;
    for(int i = l-1; i >= 0; i--)
    if(f[c][i]=='X') break;
    else if(f[c][i]=='/') return 0;
    for(int i = c+1; i < n; i++)
    if(f[i][l]=='X') break;
    else if(f[i][l]=='/') return 0;
    for(int i = c-1; i >= 0; i--)
    if(f[i][l]=='X') break;
    else if(f[i][l]=='/') return 0;
    return 1;
}
void printf_permutation(int c, int l, int num)
{
    int t = 0;
    f[c][l] = '/';
    for(int i = 0; i < n; i++)
    for(int j = 0; j < n; j++)
    if(is_caninset(i,j)){t++; printf_permutation(i,j,num+1);}
    if(!t)  max = max<num?num:max;
    f[c][l] = '.';
}
int main ()
{
    while(scanf("%d",&n)&&n)
    {
        getchar();
        for(int i = 0; i < n; i++, getchar())
        for(int j = 0; j < n; j++)
        scanf("%c",&f[i][j]);
        max = 0;
        for(int i = 0; i < n; i++)
        for(int j = 0; j < n; j++)
        if(is_caninset(i,j)) printf_permutation(i,j,1);
        printf("%d\n",max);
    }
    return 0;
}
再贴一下12ms的代码:

#include <cstdio>
char f[5][5];
int  n;
int is_caninset(int c, int l)
{
    if(f[c][l]=='X'||f[c][l]=='/'||f[c][l]=='o')return 0;
    for(int i = l-1; i >= 0; i--)
    if(f[c][i]=='X') break;
    else if(f[c][i]=='/') return 0;
    for(int i = c-1; i >= 0; i--)
    if(f[i][l]=='X') break;
    else if(f[i][l]=='/') return 0;
    return 1;
}
int printf_permutation(int c, int l)
{
    int t = 0, max = 0;
    f[c][l] = '/';
    for(int i = c; i < n; i++)
    for(int j = (i==c?l+1:0); j < n; j++)
    if(is_caninset(i,j)){t = printf_permutation(i,j)+1; max = max<t?t:max;}
    f[c][l] = '.';
    return max;
}
int main ()
{
    int max, t;
    while(scanf("%d",&n)&&n)
    {
        getchar();
        for(int i = 0; i < n; i++, getchar())
        for(int j = 0; j < n; j++)
        scanf("%c",&f[i][j]);
        max = 0;
        for(int i = 0; i < n; i++)
        for(int j = 0; j < n; j++)
        if(is_caninset(i,j)) {t = printf_permutation(i,j)+1; max = max < t? t: max;}
        printf("%d\n",max);
    }
    return 0;
}



posted on 2013-02-21 11:22  Primo...  阅读(145)  评论(0)    收藏  举报