不会停止换行……求解,9wa1tle,求调

P1219 [USACO1.5] 八皇后 Checker Challenge

wzh0910 @ 2023-07-27 15:47:53

#include<iostream>
using namespace std;
int a[15],k,c=0;
long long cnt;
bool check(int n)
{
    for(int i=1;i<n;i++)
    {
        if(a[i]==a[n]||i-a[i]==n-a[n]||i+a[i]==n+a[n])
        {
            return 0;
        }
    }
    return 1;
}
void dfs(int n)
{
    if(n==k+1)
    {
        cnt++;

        for(int i=1;i<=k;i++)
        {
            if(c>=3)break;
            cout<<a[i]<<" ";
        }
        c++;
        cout<<"\n";
    }
    else
    {
        for(int i=1;i<=k;i++)
        {
            a[n]=i;
            if(check(n))
            {
                dfs(n+1);
            }
        }
    }
} 
int main()
{
    cin>>k;
    dfs(1);
    cout<<cnt;
    return 0; 
}

by DioxygenDifluoride @ 2023-07-27 15:51:54

@wzh0910

#include<iostream>
using namespace std;
int a[15],k,c=0;
long long cnt;
bool check(int n)
{
    for(int i=1;i<n;i++)
    {
        if(a[i]==a[n]||i-a[i]==n-a[n]||i+a[i]==n+a[n])
        {
            return 0;
        }
    }
    return 1;
}
void dfs(int n)
{
    if(n==k+1)
    {
        cnt++;

        for(int i=1;i<=k;i++)
        {
            if(c>=3){
                return;
            }
            cout<<a[i]<<" ";
        }
        c++;
        cout<<"\n";
    }
    else
    {
        for(int i=1;i<=k;i++)
        {
            a[n]=i;
            if(check(n))
            {
                dfs(n+1);
            }
        }
    }
} 
int main()
{
    cin>>k;
    dfs(1);
    cout<<cnt;
    return 0; 
}

by DioxygenDifluoride @ 2023-07-27 15:52:32

@wzh0910 把第二行的 break 换成 return


by jrzhr @ 2023-07-27 15:57:42

打表


by wzh0910 @ 2023-07-27 16:02:17

@woshishabi250 谢谢


by wzh0910 @ 2023-07-27 16:03:07

现在最后一点tle了……


by DioxygenDifluoride @ 2023-07-27 16:13:29

@wzh0910 在提交时把 O2 打钩


by wzh0910 @ 2023-07-27 16:16:10

@woshishabi250 谢谢,AC了


|