PAT (Advanced Level) Practice A1128 N Queens Puzzle (20 分) (集合、N皇后問題)

原題鏈接

#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
using namespace std;

const int MAX = 1010;

int Q[MAX], K, N;

int main()
{
    scanf("%d", &K);
    for(int i=0; i<K; i++)
    {
        scanf("%d", &N);
        set<int> S;//用集合來判斷是否有重合數據;或者用一個visited布爾類型數組
        for(int j=1; j<=N; j++)
        {
            scanf("%d", &Q[j]);
            S.insert(Q[j]);
        }
        if(S.size() != N) printf("NO\n");
        else
        {
            bool flag = 0;
            for(int j=1; j<=N; j++)
            {
                for(int k=j+1; k<=N; k++)
                {
                    if(abs(j-k) == abs(Q[j]-Q[k]))//在一個對角線上,則不合法
                    {
                        flag = 1;
                        break;
                    }
                }
                if(flag) break;
            }
            if(flag) printf("NO\n");
            else printf("YES\n");
        }
    }
	return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章