WA+TLE

P1219 [USACO1.5] 八皇后 Checker Challenge

zhengyi0402 @ 2024-10-07 08:54:25

#include<bits/stdc++.h>
#define int long long
using namespace std;
int n;
vector<int> v;
int ans = 0;
set<int> s;
int num = 0;
void dfs(int x){
    if(x==n+1){
        int num1 = 0,num2 = 0;
        for(int i = 0;i < n;i++){
            if(i+1==v[i]){
                num1++;
            }
        } //第一对角线 
        for(int i = 0;i < n;i++){
            if(n-i==v[i]){
                num2++;
            }
        }//第二对角线 
        if(num1<=1&&num2<=1){
            if(num<3){
                for(int i = 0;i < n;i++){
                    cout<<v[i]<<' ';
                }cout<<'\n';
            }
            ++ans;++num;
            return ;
        }
    }
    for(int i = 1;i <= n;i++){
        if(!s.count(i)){
            v.push_back(i);
            s.insert(i);
            dfs(x+1);
            s.erase(i);
            v.pop_back();
        }
    }
}
signed main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    cin>>n;
    dfs(1);cout<<ans; 
    return 0;
    //十年OI一场空,define int 见祖宗。
    //十年OI一场空,不开long long见祖宗。
}

7~#10 TLE,其它WA

能告诉萌新为什么吗????


by Moco_jof @ 2024-10-07 09:02:49

#include <iostream>
#include <cstdio>
using namespace std;
int a[15],ans,n;
bool b[15],c[100],d[100];
void search(int);
void print();
int main(){
    scanf("%d",&n);
    search(1);
    printf("%d",ans);
    return 0;
}
void search(int i){
    for(int j=1;j<=n;j++){
        if((!b[j])&&(!c[i+j])&&(!d[i-j+n])){
            a[i]=j;
            b[j]=1;
            c[i+j]=1;
            d[i-j+n]=1;
            if(i==n){
                print();
            }else{
                search(i+1);
            }
            b[j]=0;
            c[i+j]=0;
            d[i-j+n]=0;
        }
    }
}
void print(){
    if(ans<=2){
        for(int i=1;i<=n;i++){
            printf("%d ",a[i]);
        }
        printf("\n");
    }
    ans++;
}

by Moco_jof @ 2024-10-07 09:03:26

正解不需要这么复杂


by Moco_jof @ 2024-10-07 09:04:19

好像不需要set


by zhengyi0402 @ 2024-10-07 09:13:58

@Moco_jof 这个代码究竟错在哪儿呢?


by Moco_jof @ 2024-10-07 09:20:37

其实第一、二对角线只需要数组来存,递归里循环不TLE就怪了


by Moco_jof @ 2024-10-07 09:21:09

WA是你循环写错了@zhengyi0402


by zhengyi0402 @ 2024-10-07 09:26:30

@moco_jof是哪个循环能告诉我吗?


by Moco_jof @ 2024-10-07 11:50:29

if(x==n+1){
        int num1 = 0,num2 = 0;
        for(int i = 0;i < n;i++){
            if(i+1==v[i]){
                num1++;
            }
        } //第一对角线 
        for(int i = 0;i < n;i++){
            if(n-i==v[i]){
                num2++;
            }
        }//第二对角线 
        if(num1<=1&&num2<=1){
            if(num<3){
                for(int i = 0;i < n;i++){
                    cout<<v[i]<<' ';
                }cout<<'\n';
            }
            ++ans;++num;
            return ;
        }
    }

这个


|