5114_ 2025-03-10 20:03 采纳率: 33.3%
浏览 10
已结题

C++全排列,运用dfs算法,代码不报错,但是运行答案不对


#include <bits/stdc++.h>
#define endl '\n'
typedef long long ll;
using namespace std;
const int N=10000;
int a[N]={0},b[N]={0};  //原数组和临时存放排序的数组 
int c[N]={0};  //用来标记第i个元素有没有用 
int n;  //输入的元素个数
void dfs(int k){
    if(k==n){
        for(int i=0;i<n;i++){
            cout<<b[i]<<" ";
        }
        cout<<endl;
    }
    else{
        for(int i=0;i<n;i++){
            if(c[i]==0){
                b[k]=a[i];
                c[i]=1;
                dfs(k+1);
                c[i]=0;
            }
        }
    }
}
void slove(){
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    dfs(0);
}
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t=1;
    //cin>>t;
    while(t)
    slove();
    return 0;
}
  • 写回答

4条回答 默认 最新

  • 宝码香车 优质创作者: JavaScript技术领域 2025-03-10 20:17
    关注
    让【宝码香车】来帮你解答,本回答参考DeepSeek编写,并整理提供,如果还有疑问可以点击头像关注私信或评论。
    如果答案让您满意,请采纳、关注,非常感谢!

    你的代码整体思路是正确的,使用了深度优先搜索(DFS)来生成全排列。不过,代码中存在一个小问题,导致程序无法正常结束。具体来说,while(t) 这个循环条件会导致程序无限循环,因为 t 的值始终为 1,没有在循环中被修改。

    问题分析:

    1. 无限循环问题while(t) 中的 t 始终为 1,导致程序无法退出循环。
    2. 输入问题:如果输入的元素个数 n0,程序不会输出任何结果,但也不会报错。

    解决方案:

    1. 修复无限循环问题:你可以通过修改 while(t) 的条件来避免无限循环。例如,你可以将 t 设置为 0 或者在 slove() 函数中处理输入后退出循环。
    2. 输入处理:确保输入的元素个数 n 大于 0,否则程序不会输出任何结果。

    修改后的代码:

    #include <bits/stdc++.h>
    #define endl '\n'
    typedef long long ll;
    using namespace std;
    const int N=10000;
    int a[N]={0},b[N]={0};  //原数组和临时存放排序的数组 
    int c[N]={0};  //用来标记第i个元素有没有用 
    int n;  //输入的元素个数
    
    void dfs(int k){
        if(k==n){
            for(int i=0;i<n;i++){
                cout<<b[i]<<" ";
            }
            cout<<endl;
        }
        else{
            for(int i=0;i<n;i++){
                if(c[i]==0){
                    b[k]=a[i];
                    c[i]=1;
                    dfs(k+1);
                    c[i]=0;
                }
            }
        }
    }
    
    void slove(){
        cin>>n;
        for(int i=0;i<n;i++){
            cin>>a[i];
        }
        dfs(0);
    }
    
    int main(){
        ios::sync_with_stdio(0);
        cin.tie(0);
        cout.tie(0);
        int t=1;
        //cin>>t;
        while(t--){
            slove();
        }
        return 0;
    }
    

    解释:

    1. **while(t--)**:将 while(t) 改为 while(t--),这样 t 会在每次循环后递减,最终变为 0,从而退出循环。
    2. 输入处理:确保输入的元素个数 n 大于 0,否则程序不会输出任何结果。

    测试:

    你可以输入以下数据进行测试:

    3
    1 2 3
    

    输出应该为:

    1 2 3 
    1 3 2 
    2 1 3 
    2 3 1 
    3 1 2 
    3 2 1 
    

    这样修改后,程序应该能够正确输出全排列,并且不会陷入无限循环。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 3月23日
  • 已采纳回答 3月15日
  • 创建了问题 3月10日