生成随机图

时间:2016-04-23 02:45:53

标签: c++ graph

每当我尝试将adj_matrix [u] [v] == adj_matrix [v] [u]用于相同的重量时,我都需要帮助它不适用,任何人都可以告诉我我是否在正确的路径上?

有没有办法将没有边的矩阵设置为X而不是0?

  int gen_random_graph(int n)
 {
    srand(time(0));
    int adj_matrix[n][n];
    for(int u = 0; u < n; u++)
    {
        for (int v = u; v < n; v++)   //generating a N x N matrix  based on the # of vertex input
        {
            bool edgeOrNot = rand() % 2;   //decide whether it has an edge or not
            adj_matrix[u][v] = adj_matrix[v][u] = edgeOrNot;
            cout << u << " " << v << " " << adj_matrix[u][v] << endl;
            if(adj_matrix[u][v] == true)
            {
                adj_matrix[v][u] = true;
                if(u == v)                            //We can't have i = j in an undirected graph
                {
                    adj_matrix[u][v] = -1;
                }
                cout << u << " " << v << " " << adj_matrix[u][v] << endl;
            }
            else
            {
                adj_matrix[v][u] = -1;
                cout << u << " " << v << " " << adj_matrix[u][v] << "else" <<  endl;
            }
        }

    }

    for(int i = 0; i < n; i++)
    {
        for(int j = i; j < n; j++)           //create the N x N with edges and sets the weight between the edge randomly
        {
            if(adj_matrix[i][j] == true)
            {
                    int weight1 = rand()%10 + 1;
                    adj_matrix[i][j] = adj_matrix[j][i] = weight1;
                    cout << " ( " << i << "," << j << " ) " << "weight: " << adj_matrix[i][j] << endl;
            }
        }
    }
}
int main()
{
    int N;
    cout << "Enter number of vertices" << endl;
    cin >> N;
    gen_random_graph(N);

    return 0;
}

2 个答案:

答案 0 :(得分:1)

相反&#39; X&#39;我建议使用-1值。有一个样本:

void gen_random_graph(int n) {
    srand(time(0));
    int adj_matrix[n][n];

    for(int u = 0; u < n; u++) {
        for (int v = u; v < n; v++) { //you don't need to calculate weight twice so loop starts from u
            if(v == u) {
                adj_matrix[u][v] = -1;
            }
            else {
                int weight = rand() % 10 - 1;
                adj_matrix[u][v] = adj_matrix[v][u] = weight;
            }
        }
    }
}

现在您可以检查边缘的值。对于-1,它不存在。

答案 1 :(得分:0)

我不确定你的算法等等。使用int adj_matrix存储bool是一回事,但存储'X'char是我应避免的。

为了存储相同的重量,我会尝试:

const int weight = rand() % 10 + 1;
adj_matrix[u][v] = weight;
adj_matrix[v][u] = weight;

编译器可能会尝试两次调用rand(),每个语句一次。在上文中,您只需调用rand()一次。

一般情况下,我会使用STL容器,例如std::vector<int>std::vector<std::vector<int>>,尽管后者从内存占用的角度来看并不理想。

而不是'X'我会使用std::numeric_limits<int>::minmax,而rand() % 10 + 1可能不等于<?php global $product; global $wpdb; $locations = get_the_terms( $product->ID, 'pa_location'); foreach ( $locations as $locationz ) { $location = $locationz->name; } $sql = "SELECT * FROM rates WHERE location = '" . $location . "';"; $query = $wpdb->get_results($sql); foreach ( $query as $price ) { $regularprice = $price->fareprice; } ?>