在C中进行优化的有效方法是什么

时间:2019-07-03 15:16:27

标签: c optimization

我在比赛中遇到了这个问题。问题如下。

https://www.screencast.com/t/eWuBxapaA

https://www.screencast.com/t/qqhWUoytyvF0

所以基本上有一个指向其他节点的节点列表。一个节点只能指向另一个节点,不能指向多个节点,但是一个节点可以由多个节点指向,但是只能有一个如图所示退出该列表。该列表包含n个值,代表每个第i个节点指向的节点。如果一个节点没有指向任何其他节点,则以-1表示。节点数N的像元编号从0到N-1。需要的结果是找到列表中存在最大权重节点的节点。节点的权重是节点号的总和(第i个索引)指向它。

下面是我的代码。怎么了?我错过了什么吗?如果没有,我可以通过什么方式对其进行优化?

int main()
{
 long m;  /*this is for no of test cases*/
 long i,j;
 scanf("%ld",&m);
 for(i=0;i<m;i++)
 {
  long n; /*number of nodes*/
  long k=-999,l;  /*k to keep track of max weight and l for the node*/
  scanf("%ld",&n);
  long a[n],b[n];  /*arrays of size n to store nodes*/
  for(j=0;j<n;j++)
  { 
   scanf("%ld",&a[j]);  /*taking inputs of the nodes that points others */
   b[j]=0;  /*initially all indexes are 0 and b array will store the weights*/
  } 
  for(j=0;j<n;j++)
  { 
   if(a[j]==-1)
   {
     /*this will do noting as such nodes point to nothing*/    
   }
   else
   {
     b[a[j]]=b[a[j]]+j+1;  /*updating the weight at a[j]-th index in b array and its j+1 but not just j bcoz j is the index which starts from 0 which is actually the 1st node*/
     if(b[a[j]]>k)
     {
      k=b[a[j]];   /*keeping track of max weight till now*/
      l=j;         /*keeps track of index(node number) with max weight till now*/
     }
   } 
  }
  printf("%ld",l+1);  /*prints the node with max weight for the i-th test case*/ 
 }
 return 0;
}

感谢阅读!

0 个答案:

没有答案
相关问题