87分求助

P1219 [USACO1.5] 八皇后 Checker Challenge

Martin0310 @ 2024-08-27 18:48:11

#10超时,其它正确。\ 代码:

#include<bits/stdc++.h>
using namespace std;
int queens[13][13],place[13],attack[13][13],k,c;
int d[8][2]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,-1}};
void check(bool x,bool y,int attx,int atty,int n)
{
    if(x && y)
    {
        if(attack[attx][atty]==0) attack[attx][atty]=n;
    }
}
void back(int n)
{
    for(int i=0;i<k;i++)
    {
        for(int j=0;j<k;j++)
        {
            if(attack[i][j]==n) attack[i][j]=0;
        }
    }
}
void queen(int n)
{
    if(n==k+1)
    {
        c++;
        if(c<=3)
        {
            for(int i=0;i<k;i++) cout<<place[i]+1<<' ';
            cout<<'\n';
        }
        return;
    }
    for(int i=0;i<k;i++)
    {
        if(attack[n-1][i]==0)
        {
            int attx=n-1,atty=i;
            for(int j=0;j<k;j++)
            {
                check(attx-j>=0,atty-j>=0,attx-j,atty-j,n);
                check(attx-j>=0,1,attx-j,atty,n);
                check(attx-j>=0,atty+j<k,attx-j,atty+j,n);
                check(1,atty-j>=0,attx,atty-j,n);
                check(1,1,attx,atty,n);
                check(1,atty+j<k,attx,atty+j,n);
                check(attx+j<k,atty-j>=0,attx+j,atty-j,n);
                check(attx+j<k,1,attx+j,atty,n);
                check(attx+j<k,atty+j<k,attx+j,atty+j,n);
            }
            queens[attx][atty]=1;
            place[n-1]=i;
            queen(n+1);
            back(n);
        }
    }
}
int main()
{
    cin>>k;
    queen(1);
    cout<<c;
    return 0;
}

by Martin0310 @ 2024-08-27 18:52:40

超时的测试点结果没有问题:


by Martin0310 @ 2024-08-27 18:53:39

@Martin0310 是#8超时


by hehe_666 @ 2024-09-06 10:02:36

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;

int a[55], n, k, cnt; 
bool hang[55], lie[55], d1[55], d2[55];

void dfs(int step)
{
    if(step > n)
    {
        if(cnt <= 2)
        {
            for(int i = 1; i <= n; i++)
            {
                cout << a[i] << " ";
            }
            cout << endl;
        }
        cnt++;

    }
    for(int i = 1; i <= n; i++)
    {
        int x = step, y = i;
        if(hang[x] || lie[y] || d1[x - y + n] || d2[x + y]) continue;
        hang[x] = lie[y] = d1[x - y + n] = d2[x + y] = true;
        a[step] = i;
        dfs(step + 1);
        hang[x] = lie[y] = d1[x - y + n] = d2[x + y] = false;
    }
}

int main()
{
    cin >> n;
    k = 3;
    dfs(1);
    cout << cnt;
    return 0;
}

|