题解:P13493 【MX-X14-T3】心电感应

· · 题解

题目简述

小C和Miku有 n 个朋友,每个朋友有 m 个特征。小C已知Miku心中想的朋友是谁,但需要通过提问特征问题(特征 x 是否为 y)来让Miku确信小C已唯一确定该朋友。要求对每个朋友 i,输出小C最少提问次数,使得通过提问能唯一确定朋友 i(即排除所有其他朋友)。若无法确定,输出 -1。

思路分析

  1. 问题转化:对每个目标朋友 i,寻找最小提问集合,使得这些提问能将 i 与其他所有朋友区分开。即对于每个其他朋友 j \neq i,存在至少一个提问使得 i 和 j 在该特征上的值不同,且该提问的答案能排除 j。
  2. 策略:小C知道目标朋友的特征值,因此每次提问特征 x 时,会问目标朋友的特征值 a_{i,x}。这样目标朋友 i 会被保留,而特征 x 值不等于 a_{i,x} 的其他朋友会被排除。
  3. 实现:对每个朋友 i,使用DFS枚举所有特征的选择(提问或不提问):
    • 状态:当前特征 x、目标朋友 y、已提问次数 cnt、剩余朋友数 rest。
    • 剪枝:当 cnt 超过当前最优解时返回。
    • 终止条件:若 rest=1(只剩目标朋友),更新最优解。
    • 选择:跳过当前特征,或提问当前特征(排除特征值不同的朋友)。
  4. 特判:无法区分,输出 -1。

C++代码

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int n,m,a[21][21];
int ans;
bool passed[21];
// DFS搜索:x-当前特征, y-目标朋友, cnt-已提问数, rest-剩余朋友数
void DFS(int x,int y,int cnt,int rest){

    if(x>m){              // 所有特征已考虑完
        if(rest==1)        // 只剩目标朋友,更新答案
            ans=min(ans,cnt);
        return;
    }
    if(cnt>=ans) return;   // 剪枝:已超过当前最优解

    // 选择1:不提问当前特征x
    DFS(x+1,y,cnt,rest);

    // 选择2:提问特征x(问目标朋友y的特征值a[y][x])
    vector<int> excluded;     // 记录本次排除的朋友
    for(int i=1;i<=n;i++){
        if(i==y || passed[i]) continue;
        if(a[i][x] != a[y][x]){ // 特征值不同则排除
            passed[i]=true;
            rest--;
            excluded.push_back(i);
        }
    }
    DFS(x+1,y,cnt+1,rest);

    // 回溯:恢复被排除朋友 
    for(int i:excluded){
        passed[i]=false;
        rest++;
    }
}
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            cin>>a[i][j];
    for(int i=1;i<=n;i++){
        // 初始化
        ans=(int)1e9; 
        for(int i=1;i<=20;i++) passed[i]=0;
        // 搜索
        DFS(1,i,0,n); 
        if(ans==1e9) ans=-1;
        cout<<ans<<' ';
    }
    return 0;
}