-2

考虑下表,其中 (Destination, Route) 映射到Node.

Destination_id(a)   route_id(b)   next_node(c)
  4                   1             6
  7                   1             9
  7                   2             8
  8                   4             4
  7                   3             2

例子:

Given input (Destination_id, route_id) : (7,3)
Expected output : 2

Given input (Destination_id, route_id) : (4,1)
Expected output : 2

换句话说,表中的有效映射将是:

Input    Ouput
(4, 1) ->  6
(7, 1) ->  9
(7, 2) ->  8
(8, 4) ->  4
(7, 3) ->  2

我编写的代码,我得到了完美的输出。有没有其他有效的方法来实现这个?

#include<stdio.h>


int main()
{
 int i,store;
 int a[5]={4,7,7,8,7};
 int b[5]={1,1,2,4,3};/// this will be always unique with respect to the search element of 'a' for eg.<7,1>, <7,2>
 int c[5]={6,9,8,4,2}; 
 int found_indices[5]; // array used to store indices of found entries..
 int count = 0; //n entries found;
 int ele_a, ele_b;
 printf("Enter the element to be search in array a\n");
 scanf("%d",&ele_a);
 printf("Enter the element to be search in array b\n");
 scanf("%d",&ele_b);
 // searching for the element
 for (i=0; i<5; i++)
 {    
     if (a[i]==ele_a)
     {
       found_indices[count ++] = i; // storing the index of found entry   

     }
  }
   if (count!=0) {
       for (i=0; i<count; i++)
       {
         if (b[found_indices[i]]==ele_b) 
         {
          store=found_indices[i];

         }
      }
   }
  printf("Element found %d ", c[store]);   
}
4

2 回答 2

0

试试这个:

for (i = 0; i < 5; i++) {
    if (a[i] == ele_a && ele_b == b[i]) {
        printf("Element found %d ", c[i]);
        break;
    }
}

如果映射表很大,那么哈希表就是要走的路。

于 2013-01-25T17:44:55.683 回答
0

您的程序可能会因其他一些输入而崩溃。因为store没有初始化为零。在这种情况下,考虑if (b[found_indices[i]]==ele_b)这种情况永远不会成功,那么最后在printf声明中 `c[store] 将导致崩溃。

在该语句本身内访问该c数组。if

int c_value = 0;
....

if (b[found_indices[i]]==ele_b) 
{
   c_value=c[found_indices[i]];
}
....

if (!c_value)printf("Element found %d ", c_value);

注意:我希望您不要将其保留为数组0中的元素之一。c

于 2013-01-25T17:48:37.627 回答