2015-11-01 14 views
0

我要讀圖形輸入(一次全部)(下面的示例):輸入/ C++

6 8 //no of vertices, edges 
0 1 2 //connectivity from vertex 0 to vertex 1, with weight 2 
0 2 1 
0 4 2 
1 2 4 
2 3 5 
3 4 5 
4 1 2 
4 5 5 

什麼是動態地讀取輸入的最佳方式。我必須馬上閱讀所有上述內容。我需要動態地看它,因爲邊和頂點的數量可以改變,與10000 一個maximun下不起作用:

int *twod_array; 
int N,M; //no of vertices, edges 
scanf("%d %d", &N, &M); 
twod_array = (int *)malloc(sizeof(int)*N*M); //where N = no of rows, M = no of cols 
for(i=0; i < N; i++) { 
    for(j=0; j < M; j++) { 
scanf("%d",&twod_array[i*M +j]); 
    } 
} 
for(i=0; i < N; i++) { 
    for(j=0; j < M; j++) { 
    if(twod_array[i*M +j] == "\0") { 
twod_array[i*M +j] = 0; 
    } 
    } 
} 

此外,這是在C/C曲線的最佳途徑++還是使用struct更好,因爲遍歷將完成。

+2

因爲(至少)1,以下do not工作。'&N&M'無效。它應該是'&N,&M'2。'2d_array'作爲標識符無效,因爲它不能以數字開頭。 3.其中N =沒有行,M =沒有列代表沒有意義的代碼。讓它成爲評論。 4.「N」不會影響行數或列數。 「M」是行數,而不是列數。 6.分配'2d_array [i * M + j] =「\ 0」'不要理會。它應該與''\ 0''比較或者沒有任何東西。 – MikeCAT

+0

@MikeCAT - 做了必要的修改。仍然不能按需要工作。 –

+2

另外'if(twod_array [i * M + j] =「\ 0」)'dosent compare ...應該是'=='。 – wrangler

回答

1

就加載數據而言,有很多方法。一個是使一個connectivity結構,並動態地分配數據文件的第一行基於邊緣值的數量的數組:

#include <stdio.h> 
#include <stdlib.h> 

struct connectivity { 
    int source; 
    int sink; 
    int weight; 
}; 

int main() { 
    int num_verts = 0; 
    int num_edges = 0; 
    struct connectivity *edges = NULL; 
    int i = 0; 

    scanf("%d %d\n", &num_verts, &num_edges); 

    edges = malloc(sizeof (struct connectivity) * num_edges); 

    for (i = 0; i < num_edges; i++) { 
     scanf("%d %d %d\n", &(edges[i].source), 
          &(edges[i].sink), 
          &(edges[i].weight)); 
    } 

    // use edges here 

    free(edges); 
} 

另外,請使用更清晰的變量名!

+0

Nitpick,但是'malloc(sizeof(* edges)* num_edges)'爲了讓純粹主義者喜歡我自己? :P – szczurcio

+0

*邊緣將被去引用空指針。 :/ – Jameson

+0

沒有被饋送到'sizeof'運算符。相反,它會給你「邊緣」類型​​指向的大小。 – szczurcio

1

根據我的經驗,使用Edge結構對於處理圖形問題是非常可行的。

struct Edge{ 
    int to; 
    int weight; 
    Edge(int t, int w):to(t), weight(w){}; 
}; 
std::vector<vector<Edge> > graph; 
int N,M; //no of vertices, edges 
scanf("%d %d", &N,&M); 
graph.resize(N); 
int u, v, w; 
for(int i = 0; i < M; i ++){ 
    scanf("%d %d %d", &u, &v, &w); 
    graph[u].push_back(Edge(v, w)); 
} 
+0

這看起來像C++,並且問題被標記爲C.然後OP再次在他們的問題中提及「C/C++」,所以... – szczurcio