【问题标题】:Convert vertex names of a graph into indices in C将图的顶点名称转换为 C 中的索引
【发布时间】:2019-03-08 21:20:19
【问题描述】:

我通过以下方式得到输入,其中第一行包含无向图的顶点数和边数;接下来的行包含顶点的名称,在这些顶点之间有一条边。

输入:

9 8
sainteanne fortdefrance
bassepointe latrinite
bridgetown jackmans
fortdefrance ducos
holetown bridgetown
shanty bridgetown
fortdefrance bassepointe
jackmans shanty

这意味着该图有 9 个顶点和 8 条边。上述每对中的元素之间都存在边。最终目标是在此图中找到连接的组件。

但是,使用顶点作为索引号比使用字符串更容易。因此,我正在寻找一种将上述信息转换为以下内容的方法:

0 1
2 3
4 5
1 6
7 4
8 4
1 2
5 8

我编写了以下 C 代码来读取文件并创建一个包含边的结构,其中必须存储顶点 ID。

typedef struct {
    unsigned int first;
    unsigned int second;
} edge;

int main()
{   
    unsigned int order;                   // no.of Vertices
    unsigned int n;                       // no.of Edges
    edge *edges;

    scanf("%u %u",&order,&n);
    edges = malloc(n * sizeof(edge));
    char first_string[20];
    char second_string[20];

    for (int i=0;i<n;i++)
    {
        scanf("%s %s",first_string,second_string);

    }
   }

【问题讨论】:

  • 你有什么问题?
  • 您可能正在寻找这个:stackoverflow.com/questions/838404/implementing-a-hashmap。你也可能想谷歌“simple hashmap in c
  • 如果您的数据集很小,您可以编写自己的简单映射实现(将字符串映射到整数)。那应该是大约 15-20 行代码。

标签: c string graph-algorithm


【解决方案1】:

您需要按照jabberwocky 的建议简单地实现映射(将字符串映射到整数)

  • 定义如下结构来存储字符串。

        typedef struct {
           unsigned int hashed;
           char **map;
       } hash;
    
  • 定义一个函数,如果字符串不存在则将其插入hashmap,并返回hashmap中字符串的索引。

    int insertInMap(hash *map, char *entry)

  • 将返回的索引存储到edge结构中。

    edges[i].first =insertInMap(&map,first_string); edges[i].second =insertInMap(&map,second_string)

完整代码:

typedef struct {
    unsigned int first;
    unsigned int second;
} edge;


typedef struct {
    unsigned int hashed;
     char **map;
} hash;


int insertInMap(hash *map, char *entry)
{
  int i =0;
  for (i=0;i<map->hashed;i++)
  {
    if (strcmp(map->map[i],entry) == 0)
    return i;
  }
  /* Warning no boundary check is added */
  map->map[map->hashed++] = strdup(entry);   
  return map->hashed-1;
}

int main()
{   
    unsigned int order;                   // no.of Vertices
    unsigned int n;                       // no.of Edges
    edge *edges;
    hash map;    
    scanf("%u %u",&order,&n);
    edges = malloc(n * sizeof(edge));

    map.map = malloc(n * sizeof(char*));
    map.hashed = 0;

    char first_string[20];
    char second_string[20];

    for (int i=0;i<n;i++)
    {
        scanf("%s %s",first_string,second_string);
        edges[i].first =insertInMap(&map,first_string);
        edges[i].second =insertInMap(&map,second_string);

    }

   for (int i =0;i<n;i++)
   printf("%d->%d\n", edges[i].first, edges[i].second);

   /* Do your work*/

   for (int i=0;i<n;i++)
     free(map.map[i]);
     free(map.map);
     free(edges);
}

输出:

0->1
2->3
4->5
1->6
7->4
8->4
1->2
5->8

注意:: 我没有为 hashmap 添加边界检查

【讨论】:

    猜你喜欢
    • 2017-10-29
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2015-12-30
    相关资源
    最近更新 更多