想问做visit判断和直接把全枚举后的ans/2的区别
查看原帖
想问做visit判断和直接把全枚举后的ans/2的区别
1809086
Q_YXH_Q楼主2025/7/29 15:07

就是有没有具体的一些例子, 以下是两份代码,

ans/2的

#include <iostream>
using namespace std;
int main()
{
    int n, tot = 0;
    int *a;
    cin >> n;
    a = (int *)malloc(sizeof(int) * (n + 2));
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    for (int t = 0; t < n; t++)
    {
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (a[i] + a[j] == a[t] && i != j && i != t)
                    tot++;
            }
        }
    }
    cout << tot / 2;
    free(a);
    return 0;
}

带vis的

#include <iostream>
using namespace std;
int main()
{
    int n, tot = 0,v[150]={0};
    int *a;
    cin >> n;
    a = (int *)malloc(sizeof(int) * (n + 2));
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    for (int t = 0; t < n; t++)
    {
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (a[i] + a[j] == a[t] && i != j && i != t && j != t&&v[t]==0)
                {
                    tot++;
                    v[t]=1;
                }
                    
            }
        }
    }
    cout << tot;
    free(a);
    return 0;
}
2025/7/29 15:07
加载中...