zoukankan      html  css  js  c++  java
  • Sicily 1934. 移动小球 解题报告

    题目:1934. 移动小球

    思路:

      想了很久,即使用链表在插入和删除元素的时候比较快,但用来查找删除插入的位置的时间也太长。

      看了别人的代码之后顿时开窍,用两个数组分别记录每一个球的左边和右边球的编号,这样就可以实现数组对元素的快速访问。非常高明而简单的方法!感觉有点类似于基于数组实现的双端链表。

    代码:

     1 #include<iostream>
     2 using namespace std;
     3 
     4 int lefts[500001]; //lefts[i] stores the lefts ball's number of the ball i.
     5 int rights[500001]; //rights[i] stores the rights ball's number of the ball i.
     6 
     7 void initial(int num_of_balls);
     8 
     9 int main(){
    10     int testcases;
    11     cin>>testcases;
    12     while(testcases--){
    13         int num_of_balls,num_of_commands,choice,x,y;
    14         cin>>num_of_balls>>num_of_commands;
    15         initial(num_of_balls);
    16         for(int i=0;i<num_of_commands;i++){
    17             cin>>choice>>x>>y;
    18             //take out x,and renew the old adjacent ball of x
    19             rights[lefts[x]]=rights[x];
    20             lefts[rights[x]]=lefts[x];
    21             if(choice==1){ //x is inserted y's left.
    22                 rights[lefts[y]]=x;
    23                 lefts[x]=lefts[y];
    24                 lefts[y]=x;
    25                 rights[x]=y;
    26             }else{//move x to y's right.
    27                 lefts[rights[y]]=x;
    28                 rights[x]=rights[y];
    29                 rights[y]=x;
    30                 lefts[x]=y;
    31             }
    32         }
    33         int position=0;
    34         while(num_of_balls--){
    35             cout<<rights[position]<<' ';
    36             position=rights[position];
    37         }
    38         cout<<endl;
    39     }
    40     return 0;
    41 }
    42 void initial(int num_of_balls){
    43     rights[0]=1;//point to the first ball.
    44     for(int i=1;i<=num_of_balls;i++){
    45         lefts[i]=i-1;
    46         rights[i]=i+1;
    47     }
    48 }
  • 相关阅读:
    C++实现base64编码
    php实现base64编码
    美团2016研发工程师笔试题(绑鞋带问题)
    URL encode 与 URL decode 的C语言实现
    常用排序算法集合-C实现
    用文件实现计算器要求多进程同时写
    vim操作命令-笔记
    Can't connect to local MySQL server through socket
    小程序页面跳转数据丢失
    Vue路由 --登录状态的判断
  • 原文地址:https://www.cnblogs.com/jolin123/p/3417052.html
Copyright © 2011-2022 走看看