题干:1148 Werewolf - Simple Version (20 分)
题解:(2021年2月8日21:27:10)部分题目给的示例能够运行过去,和满分的题解比较,发现对于题目最后的约束条件认识不够完整,导致后续产生了太多可能的解决方案
后续的排序和比较序列大小的代码值得借鉴,满分代码这一部分的设计过于取巧,缺少一般性,参考价值不大
// A1148.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <bits/stdc++.h>
using namespace std;
#pragma warning(disable:4996)
vector<int> an;
vector<vector<int>> cn;
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif // !ONLINE_JUDGE
int n;
cin >> n;
an.resize(n + 1);
for (int i = 1; i <= n; i++) {
cin >> an[i];
}
int tw, fw,lm;
bool flag = false;
int count = 0;
for (tw = 1; tw <= n; tw++) {
for (fw = 1; fw <= n; fw++) {
if (fw == tw) {
continue;
}
else {
for (lm = 1; lm <= n; lm++) {
if (lm == fw || lm == tw) {
continue;
}
else {
vector<int> bn(n + 1, 1);
bn[tw] = -1; bn[fw] = -1;
int c = abs(an[tw]);
if (an[tw] * bn[c] > 0) {
c = abs(an[fw]);
if (an[fw] * bn[c] < 0) {
c = abs(an[lm]);
if (an[lm] * bn[c] < 0) {
vector<int> temp = { tw,fw };
cn.push_back(temp);
//cn.push_back(fw);
flag = true;
count++;
}
}
}
}
}
}
}
}
//select
if (flag) {
for (int i = 0; i < cn.size(); i++) {
sort(cn[i].begin(), cn[i].end());
}
int j,index=-1;
for (int i = 0; i < 2; i++) {
int val = 999;
for (j = 0; j < cn.size(); j++) {
if (cn[j][i] <= val) {
val = cn[j][i];
index = j;
}
else {
cn[j][1] = 999;
}
}
}
cout << cn[index][0] <<" " << cn[index][1];
}
else {
cout << "No Solution";
}
return 0;
}
别人的满分代码
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v(n+1);
for (int i = 1; i <= n; i++) cin >> v[i];
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
vector<int> lie, a(n + 1, 1);
a[i] = a[j] = -1;
for (int k = 1; k <= n; k++)
if (v[k] * a[abs(v[k])] < 0) lie.push_back(k);
if (lie.size() == 2 && a[lie[0]] + a[lie[1]] == 0) {
cout << i << " " << j;
return 0;
}
}
}
cout << "No Solution";
return 0;
}
- 自己的满分代码,吸收改进以后的,如果题目的要求是按照递减的顺序,即从大到小的顺序或者其他的偏好从可能的多个方案里面选择的话,这种解法就需要增加和我类似的后面的步骤,不然是没法做出正确答案的
-
// A1148.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <bits/stdc++.h> using namespace std; #pragma warning(disable:4996) vector<int> an; vector<vector<int>> cn; int main() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); #endif // !ONLINE_JUDGE int n,t; cin >> n; an.resize(n + 1); for (int i = 1; i <= n; i++) { cin >> an[i]; } int w1, w2; bool flag = false; for (w1 = 1; w1 <= n; w1++) { for (w2 = w1 + 1; w2 <= n; w2++) { vector<int> bn(n + 1, 1); bn[w1] = -1; bn[w2] = -1; vector<int> lie; for (int i = 1; i <= n; i++) { if (bn[abs(an[i])] * an[i] < 0) { lie.push_back(i); } } if (lie.size() == 2 && bn[lie[0]] + bn[lie[1]] == 0) { vector<int> temp = { w1,w2 }; cn.push_back(temp); flag = true; } } } //select if (flag) { int j,index=-1; for (int i = 0; i < 2; i++) { int val = 999; for (j = 0; j < cn.size(); j++) { if (cn[j][i] <= val) { val = cn[j][i]; index = j; } else { cn[j][1] = 999; } } } cout << cn[index][0] <<" " << cn[index][1]; } else { cout << "No Solution"; } return 0; }