牛客_四个选项_C++题解

原题链接:链接;

我的代码:

cpp 复制代码
#include<iostream>
#include<vector>
using namespace std;
int m,x,y;
int cnt[5];
bool same[13][13];
int ret;
vector<int> path;
bool isSame(int pos,int cur){
    for(int i = 1;i<pos;i++){
        if(same[pos][i]&&cur!=path[i]){
            return false;
        }
    }
    return true;
}
void dfs(int pos){
    if(pos>12){
        ret++;
        return;
    }
    for(int i = 1;i<=4;i++){
        if(cnt[i]==0)continue;
        if(!isSame(pos,i))continue;
        cnt[i]--;
        path.push_back(i);
        dfs(pos+1);
        cnt[i]++;
        path.pop_back();        
    }
}
int main(){
    for(int i = 1;i<=4;i++)cin>>cnt[i];
    cin>>m;
    while(m--){
        cin>>x>>y;
        same[x][y] = same[y][x] = true;
    }
    path.push_back(0);
    dfs(1);
    cout<<ret<<endl;
    return 0;
}

需要注意的地方:
1.path.push_back(0);这是一个占位符,path是一个变长数组,里面记录着一轮dfs时,在12个选项上填写的答案。我们想让pathi表示第i个位置填写的是哪个选项,从而做出是否符合要求的判断。所以path0没有意义,但是需要占位。

2.samexy = sameyx = t;注意:x和y位置答案要一样,意味着y和x位置答案也要一样。

3.isSame函数用来判断,第pos位置填写cur是否符合题目中的m个条件中的x位置和y位置答案要一样,我们封装了这样的函数进行判断,有了path数组便可以详细记录是否满足它的要求。每一轮dfs完成后都会pop_back();所以path数组详细记录了一次dfs下去,12个选项中填写的答案。

4.cnt5数组中,cnti代表在i 还有多少个,比如cnt2==5;表示B选项还有5个没有填写进去。

5.sameij代表第i个题目和第j个题目的答案要一样。

相关推荐
会编程的小孩4 分钟前
C++ qt的安装
c++
?abc!3 小时前
(数组)581. 最短无序连续子数组
数据结构·算法·leetcode
小成202303202656 小时前
C++~07补充
开发语言·c++
hold?fish:palm6 小时前
40 二叉树的直径
c++·leetcode
解决小子6 小时前
【虚幻引擎】【C++】【GAS框架】构建角色基类、属性集、数值钳制
c++·笔记·游戏引擎·虚幻·gas·能力系统
guo_wen_qiang7 小时前
二叉树的层序遍历-使用双端队列Deque
算法·leetcode·1024程序员节
爱读书的小胖7 小时前
LeetCode 55 跳跃游戏 C 语言解题分析
c语言·数据结构·算法·leetcode·1024程序员节
lunar_coder8 小时前
【C++】如何解决智能指针的析构函数,如何实现shared_ptr的引用计数以及解决shared_ptr的循环引用
c++·1024程序员节
白白白小纯8 小时前
C++进阶.多态
c++
Navigator_Z8 小时前
LeetCode //C - 1300. Sum of Mutated Array Closest to Target
c语言·算法·leetcode