-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の要素の1つとして保持しないことを願っています。c

于 2013-01-25T17:48:37.627 に答える