题目:1-20的两个数把和告诉A,积告诉B,A说不知道是多少,B也说不知道,这时A说我知道了,B说我也知道了,问这两个数是多少?
首先提一点,题目没有说明两个数是否可以相等,我按照两个数不能相等计算
网络上的答案普遍是 2,3 和 2,4,我在一处看到了9,20。解法以数学推理为主,但尝试下,难度很高,决定用程序解决。最后跑出了3个答案:2,3;2,4;9,20。在此提出思路和代码,希望能得到更多讨论。如有错误,也希望得到大佬的指正。
思路:首先将所有可能记作S集合,每一次说算作一轮 ,每轮从S集合中删去一些可能。
知道:满足 和/积 的所有数对 且 在S集合中的,只有一个。
不知道:满足 和/积 的所有数对 且 在S集合中的,有多个。
#include<bits/stdc++.h>
using namespace std;
#define mp make_pair
#define pb push_back
vector<pair<int,int> > he(int x){
vector<pair<int,int>> f;
for(int i=1;i<=20;i++)
for(int j=i+1;j<=20;j++)
if(i+j==x){
f.pb(mp(i,j));
}
return f;
}
vector<pair<int,int> > ji(int x){
vector<pair<int,int>> f;
for(int i=1;i<=20;i++)
for(int j=i+1;j<=20;j++)
if(i*j==x){
f.pb(mp(i,j));
}
return f;
}
bool S[21][21];
bool T[21][21];
void solve(){
memset(S,0,sizeof(S));
for(int a=1;a<=20;a++)
for(int b=a+1;b<=20;b++) S[a][b] = 0;
for(int a=1;a<=20;a++)
for(int b=a+1;b<=20;b++){
auto h = he(a+b);
auto j = ji(a*b);
if(h.size()>1&&j.size()>1){
int num = 0;
for(int i=0;i<j.size();i++){
if(he(j[i].first+j[i].second).size()>1){
num++;
}
}
if(num<=1) continue;
S[a][b] = 1;
}
}
for(int a=1;a<=20;a++)
for(int b=1;b<=20;b++) T[a][b] = S[a][b];
for(int a=1;a<=20;a++)
for(int b=a+1;b<=20;b++)
if(T[a][b]){
auto h = he(a+b);
auto j = ji(a*b);
int z = 0;
for(int t=0;t<h.size();t++){
if(T[h[t].first][h[t].second]==1){
z++;
}
}
if(z!=1) S[a][b] = 0;
}
for(int a=1;a<=20;a++)
for(int b=a+1;b<=20;b++)
if(S[a][b]){
auto h = he(a+b);
auto j = ji(a*b);
int k = 0;
for(int t=0;t<j.size();t++){
if(S[j[t].first][j[t].second] == 1){
k++;
}
}
if(k==1) cout<<a<<" "<<b<<endl;
}
}
int main(){
//int T;cin >> T;while(T--)
solve();
return 0;
}