【问题标题】:This Program is giving me a Runtime error. What is the problem?这个程序给了我一个运行时错误。问题是什么?
【发布时间】:2020-09-06 17:08:54
【问题描述】:

我在 Dev C++ 中运行它,它给了我返回 1 个退出状态的 ID。我在这里做错了什么?

长度为 n 的排列是由 n 个从 1 到 n 以任意顺序排列的不同整数组成的数组。例如,[2,3,1,5,4] 是一个排列,但是 [1,2,2] 不是一个排列(2 在数组中出现两次)并且 [1,3,4] 也不是一个排列排列(n=3,但数组中有 4 个)。

令 p 为长度为 n 的任意排列。我们将 p 的指纹 F(p) 定义为 p 中相邻元素之和的排序数组。更正式地说,

F(p)=排序([p1+p2,p2+p3,…,pn−1+pn])。 例如,如果 n=4 且 p=[1,4,2,3],则指纹由 F(p)=sort([1+4,4+2,2+3])=sort( [5,6,5])=[5,5,6]。

给定一个长度为 n 的排列 p。你的任务是找到具有相同指纹的不同排列 p'。如果存在某个索引 i 使得 pi≠p′i,则认为两个排列 p 和 p′ 是不同的。

#include <bits/stdc++.h>
using namespace std;
int* fingerprint(int p[],int n)
{
    int fp[n-1];
    for(int i=0;i<n-1;i++)
    {
        fp[i]=p[i]+p[i+1];
    }
    sort(fp,fp+n-1);

    return fp;
}
void display(int p[],int n)
{
    for(int i=0;i<n;i++)
        cout<<p[i]<<" ";
    cout<<endl;
}
void equality(int p[],int* fp,int n)
{
    int* fp1=fingerprint(p,n);
    int c=0;
    for(int i=0;i<n-1;i++)
    {
        if(fp[i]!=fp1[i])
            c=1;
    }
    if(c==0)
        display(p,n);
}
void findpermutations(int p[],int n)
{
    int* fp=fingerprint(p,n);
    sort(p,p+n);
    do{
        equality(p,fp,n);
    }while(next_permutation(p,p+n));
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        int p[n];
        for(int i=0;i<n;i++)
        {
            cin>>p[i];

        }

        findpermutations(p,n);
    }
    return 0;
}

输入:

3

2

1 2

6

2 1 6 5 4 3

5

2 4 3 1 5

输出:

2 1

1 2 5 6 3 4

3 1 5 2 4

【问题讨论】:

  • 我强烈建议使用vector 而不是数组。此外cin &gt;&gt; n; int p[n] 不是有效的c++。
  • int fp[n-1]; ... return fp; --> fp 将在函数退出时被删除。因此,您正在返回一个指向没有任何意义的内存位置的指针。按照 cigien 的建议使用 vectors 是解决该问题的一种方法。

标签: c++ arrays pointers runtime-error permutation


【解决方案1】:

我看到的是 C 和 C++ 之间的混合,如果我们使用向量而不是指针(因为为什么不使用),它看起来像这样:

vector<int> fingerprint(int p[],int n)
{
    vector<int> fp;
    fp.resize(n-1);
    for(int i=0;i<n-1;i++)
    {
        fp[i]=p[i]+p[i+1];
    }
    sort(fp.begin(),fp.end());
    return fp;
}
void equality(int p[],vector<int> fp,int n)
{
    vector<int> fp1=fingerprint(p,n);
    int c=0;
    for(int i=0;i<n-1;i++)
    {
        if(fp[i]!=fp1[i])
            c=1;
    }
    if(c==0)
        display(p,n);
}
void findpermutations(int p[],int n)
{
    vector<int>fp = fingerprint(p,n); //n-1
    sort(fp.begin(),fp.end());
    do{
        equality(p,fp,n);
    }while(next_permutation(p,p+n));
}

【讨论】:

    猜你喜欢
    • 2014-11-10
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 2021-09-22
    相关资源
    最近更新 更多