列举撒谎者i,j,遍历数组得到狼。如果狼的size等于2,那么序列必须是(i,x)或(j,x) (x != i && x != j)
如果狼的size等于1,那么该人x不能是i,j。因为如果x==i || x == j,另外一个狼就得不到。当x不是i,j时,有两种可能:(x, i) (x, j)列举即可。
结果测试点3答案错误……求大佬解答
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
const int SIZE = 1005;
int peos[SIZE];
bool cmp (const pair<int, int>& a, const pair<int, int>& b) {
if (a.first != b.first) return a.first < b.first;
else return a.second < b.second;
}
int main() {
int N;
int first = -1, second;
cin >> N;
for (int i = 1; i <= N; i ++) {
cin >> peos[i];
}
int sum = 0;
vector<pair<int, int>> res;
vector<pair<int, int>> liars;
for (int i = 1; i < N; i ++) {
for (int j = i + 1; j <= N; j ++) {
//假设i和j撒谎
first = -1;
set<int> wolves;
int liarsSum = 0;
for (int k = 1; k <= N; k ++) {
if (k == i || k == j) { //撒谎的人
if (peos[k] > 0 && wolves.count(peos[k]) == 0) wolves.insert(peos[k]);
} else {
if (peos[k] < 0 && wolves.count(abs(peos[k])) == 0) wolves.insert(abs(peos[k]));
}
}
if (wolves.size() == 2) {
if (wolves.count(i) && wolves.count(j) == 0 || (wolves.count(j) && wolves.count(i) == 0)) {
for (auto x : wolves) {
if (first == -1) first = x;
else second = x;
}
if (first > second) swap(first, second);
pair<int, int> p(first, second);
res.push_back(p);
pair<int, int> p1(i, j);
liars.push_back(p1);
}
} else if (wolves.size() == 1) {
if (wolves.count(i) == 0 && wolves.count(j) == 0) {
int t1, t2, ti = i, tj = j;
for (auto x : wolves) {
t1 = x;
t2 = x;
}
if (t1 > ti) swap(t1, ti);
if (t2 > tj) swap(t2, tj);
pair<int, int> p1(t1, ti);
pair<int, int> p2(t2, tj);
res.push_back(p1);
res.push_back(p2);
pair<int, int> p3(i, j);
liars.push_back(p3);
}
}
}
}
if (res.size() == 0) cout << "No Solution" << endl;
else {
sort(res.begin(), res.end(), cmp);
cout << res[0].first << " " << res[0].second << endl;
}
cin >> N;
return 0;
}
借鉴了网上的做法,将i、j看作狼
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
const int SIZE = 1005;
int peos[SIZE];
bool cmp (const pair<int, int>& a, const pair<int, int>& b) {
if (a.first != b.first) return a.first < b.first;
else return a.second < b.second;
}
int main() {
int N;
int first = -1, second;
cin >> N;
for (int i = 1; i <= N; i ++) {
cin >> peos[i];
}
int sum = 0;
vector<pair<int, int>> res;
int a[SIZE];
for (int i = 1; i < N; i ++) {
for (int j = i + 1; j <= N; j ++) {
//i、j是狼
fill(a, a + SIZE, 1);
a[i] = a[j] = -1;
vector<int> liars;
for (int k = 1; k <= N; k ++) {
if (peos[k] * a[abs(peos[k])] < 0) liars.push_back(k);
}
if (liars.size() == 2 && a[liars[0]] != a[liars[1]]) {
pair<int, int> p(i, j);
res.push_back(p);
}
}
}
if (res.size() == 0) cout << "No Solution" << endl;
else {
sort(res.begin(), res.end(), cmp);
cout << res[0].first << " " << res[0].second << endl;
}
cin >> N;
return 0;
}