只有例题对了,球解

P1219 [USACO1.5] 八皇后 Checker Challenge

wangshushu @ 2024-08-17 14:02:47

/*

*/
#include<bits/stdc++.h>
using namespace std;
int n=0;
int sum=0;
int c[100]={};int d[100]={};
int b[100]={};
int a[3][6]={};
int zongsu=0;
int num=0;
void quing(int m)
{
    if(m>n)
    {
        zongsu++;
        if(zongsu<3)
        {
            for(int i=0;i<=n-1;i++)
            {
                cout <<a[num][i]<<' ';
            }
            cout <<endl;
            num++;
        }
        return;
    }
    for(int i=1;i<=n;i++)
    {
        if(b[i]||c[m+i]||d[m-i+n])
        {
            continue;
        }
        b[i]=1;
        c[m+i]=1;
        d[m-i+n]=1;
        a[num][m-1]=i;
        quing(m+1);
        a[num][m-1]=0;
        b[i]=0;
        c[m+i]=0;
        d[m-i+n]=0;
    }
}

int main()
{   
    cin >>n;
    quing(1);
    cout <<zongsu;
    return 0;
}

by tangyiqi @ 2024-08-20 14:50:46

@wangshushu
用我的AC代码吧

#include <bits/stdc++.h>
using namespace std;
int a[15],n,ans;
bool check(int row,int col){
    for(int i = 1;i<row;i++){
        if(a[i] == col || abs(a[i]-col) == abs(row-i))return false;
    }
    return true;
}
void dfs(int k){
    if(k>n){ans++;if(ans>3)return;for(int i = 1;i<=n;i++)printf("%d ",a[i]);printf("\n");return;}
    for(int i = 1;i<=n;i++){
        if(check(k,i)){a[k] = i;dfs(k+1+1+1-2);a[k] = 0;}
    }
}
int main(){
    scanf("%d",&n);
    dfs(1);
    printf("%d ",ans);
}

求关,按下关注后加入“https://www.luogu.com.cn/team/86926”团队


by wangshushu @ 2024-08-28 11:11:47

@tangyiqi 关注了


by hehe_666 @ 2024-09-06 10:03:31

@wangshushu

#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;
}

|