⬆︎
×

[PAT-A] 1148 Werewolf – Simple Version

Hyplus目录

Java

import java.io.*;
import java.util.*;

public class Main {
    static final int N = 110;
    static int n;
    static int[] statements;
    static Set<Integer> liars = new HashSet<>();

    static boolean check(int wolf1, int wolf2) {
        liars.clear();
        for (int i = 1; i <= n; i++) {
            int accusedPlayer = Math.abs(statements[i]);
            boolean saidWolf = statements[i] < 0;

            if (saidWolf) {
                if (accusedPlayer != wolf1 && accusedPlayer != wolf2) {
                    liars.add(i);
                }
            } else {
                if (accusedPlayer == wolf1 || accusedPlayer == wolf2) {
                    liars.add(i);
                }
            }
        }

        if (liars.size() != 2) return false;

        int lyingWolves = 0;
        for (int liar : liars) {
            if (liar == wolf1 || liar == wolf2) {
                lyingWolves++;
            }
        }
        return lyingWolves == 1;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        n = Integer.parseInt(br.readLine());
        statements = new int[N];

        for (int i = 1; i <= n; i++) {
            statements[i] = Integer.parseInt(br.readLine());
        }

        for (int i = 1; i <= n; i++) {
            for (int j = i + 1; j <= n; j++) {
                if (check(i, j)) {
                    System.out.println(i + " " + j);
                    return;
                }
            }
        }

        System.out.println("No Solution");
    }
}

C++

#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <unordered_set>

using namespace std;

const int N = 110;

int n;
int p[N];
unordered_set<int> st;

void check(int w1, int w2) {
    for (int i = 1; i <= n; ++i) {
        int q = abs(p[i]);
        bool is_w = (p[i] < 0);

        if (q != w1 && q != w2 && is_w) st.insert(i);
        else if ((q == w1 || q == w2) && !is_w) st.insert(i);
    }
}

int main() {
    cin >> n;
    for (int i = 1; i <= n; ++i) cin >> p[i];

    for (int i = 1; i <= n; ++i)
        for (int j = i; j <= n; ++j)
            if (i != j) {
                st.clear();
                check(i, j);

                if (st.size() != 2) continue;

                int cnt = 0;
                for (auto lier: st)
                    if (lier == i || lier == j) cnt++;
                if (cnt != 1) continue;

                cout << i << " " << j << endl;
                return 0;
            }

    cout << "No Solution" << endl;
    return 0;
}

发表评论