G - Boxes in a Line (数组模拟双向链表)

本文探讨了一种通过数组模拟双向循环链表的方法来高效处理一系列命令操作的问题。具体包括移动、交换及反转等四种类型的操作,通过对原始列表实现方式的优化,显著提高了算法效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >




G - Boxes in a Line  

You have n boxes in a line on the table numbered 1...n from left to right. Your task is to simulate 4 kinds of commands:
• 1 X Y : move box X to the left to Y (ignore this if X is already the left of Y )
• 2 X Y : move box X to the right to Y (ignore this if X is already the right of Y )
• 3 X Y : swap box X and Y
• 4: reverse the whole line.
Commands are guaranteed to be valid, i.e. X will be not equal to Y .
For example, if n = 6, after executing 1 1 4, the line becomes 2 3 1 4 5 6. Then after executing 2 3 5, the line becomes 2 1 4 5 3 6. Then after executing 3 1 6, the line becomes 2 6 4 5 3 1. Then after executing 4, then line becomes 1 3 5 4 6 2


Input

There will be at most 10 test cases. Each test case begins with a line containing 2 integers n, m (1 ≤ n,m ≤ 100,000). Each of the following m lines contain a command.


Output

For each test case, print the sum of numbers at odd-indexed positions. Positions are numbered 1 to n from left to right.

Sample Input

6 4
1 1 4
2 3 5
3 1 6
4

6 3
1 1 4
2 3 5
3 1 6

100000 1
4
Sample Output
Case 1: 12
Case 2: 9
Case 3: 2500050000  

我用list写的超时了。。。
代码:                 

#include<iostream>
#include<cstdio>
#include<list>
#include<algorithm>
using namespace std;

int main(void)
{
	list<int> lis;
	int n,m,j=1;
	while(~scanf("%d %d",&n,&m))
	{
		int i;
		for(i=1;i<=n;i++)
		{
			lis.push_back(i);
		}
		while(m--)
		{
			int run;
			scanf("%d",&run);
			if(run==1)
			{
				int x,y;
				scanf("%d %d",&x,&y);
			    list<int>::iterator it;
				it=find(lis.begin(),lis.end(),y);
				--it;
				if(*it!=x)
				{
					lis.remove(x);
					lis.insert(it,x);
				}
			}
			else if(run==2)
			{
				int x,y;
				scanf("%d %d",&x,&y);
				list<int>::iterator it;
				it=find(lis.begin(),lis.end(),y);
				++it;
				if(it==lis.end())
				{
					lis.remove(x);
					lis.push_back(x);
				}
				else if(*it!=x)
				{
					lis.remove(x);
					it=lis.insert(it,x);
				}
			}
			else if(run==3)
			{
				int x,y,temp;
				scanf("%d %d",&x,&y);
				list<int>::iterator it1=find(lis.begin(),lis.end(),x);
				list<int>::iterator it2=find(lis.begin(),lis.end(),y);
				temp=*it1;
				*it1=*it2;
				*it2=temp;
			}
			else
			{
				lis.reverse();
			}
		}
		long long sum=0;
		list<int>::iterator it;
		for(it=lis.begin();it!=lis.end();it++)
		{
			sum+=*it;
			it++;
		}
		printf("case %d: %lld\n",j++,sum);
		lis.clear();
	}
	return 0;
} 
最后网上查了下,学会了用数组模拟链表的方式。(第一次学)

#include<iostream> 
#include<cstdio>
#include<cstring>
using namespace std;  
int L[100010];//   
int R[100010];  
void Link(int &x,int &y) //左右链接,注意顺序 
{  
    R[x]=y;  
    L[y]=x;  
}  
  
int main(void)  
{  
    int i,j=0;  
    int n,m;  
    while(~scanf("%d %d",&n,&m))  
    {  
        R[0]=1;  
        L[0]=n;  
        for(i=1;i<=n;i++)  
        {  
            L[i]=i-1;  
            R[i]=i+1;  
        }  
		R[n]=0; 
        int op,x,y,dir=1,Ry,Rx,Lx,Ly;  
        while(m--)  
        {  
            scanf("%d",&op);  
            if(op!=4)  
            scanf("%d %d",&x,&y);  
            else  
            {  
                dir=!dir; 
                continue;  
            }  
            if(!dir&&op!=3)  
            {  
                op=3-op;//  如果链表逆转了,则左右相反 
            }  
            if(op==1&&R[x]==y) continue; //考虑已经满足条件的情况 
            if(op==2&&L[x]==y) continue;  
            Ry=R[y],Rx=R[x],Lx=L[x],Ly=L[y];  
            if(op==1)  
            {  
                Link(Lx,Rx);  
                Link(Ly,x);  
                Link(x,y); //自己想象 ... Lx x Rx....Ly y Ry ..... 
            }  
            else if(op==2)  
            {  
                Link(Lx,Rx);  
                Link(y,x);  
                Link(x,Ry);  
            }  
            else if(op==3)  
            {  
                if(R[x]==y)  //..Lx x (Rx Ly) y Ry ...
                {  
                    Link(Lx,y);  
                    Link(y,x);  
                    Link(x,Ry);  
                }  
                else if(L[x]==y)  //..Ly y (Ry Lx) x Rx ...
                {  
                    Link(Ly,x);  
                    Link(x,y);  
                    Link(y,Rx);  
                }  
                else  
                {  
                    Link(Lx,y);  
                    Link(y,Rx);  
                    Link(Ly,x);
                    Link(x,Ry);
                }  
            }  
        }  
        int b=0;
		long long ans=0; 
        for(i=1;i<=n;i++)  
        {  
            b=R[b];//R[0]指向第一个元素从R[0]开始 
            if(i&1)//奇数 
			{
				ans+=b;
            }
        } 
        if(!(dir)&&!(n%1))//考虑链表逆转的情况//n是奇数时不用考虑 
        {
        	ans=(long long)n*n/2+n/2-ans;
        }
        printf("Case %d: %lld\n",++j,ans);
    }  
    return 0;  
 }   

### 动态数组双向链表的特点与区别 动态数组(如 Java 中的 `ArrayList`)和双向链表(如 Java 中的 `LinkedList`)是两种常见的线性数据结构,它们各自具有独特的特点和适用场景。以下是它们的特点、区别及使用场景的详细比较。 #### 1. 特点 - **动态数组** 动态数组是一种基于固定大小数组实现的数据结构,能够根据需要自动调整大小[^3]。它在内存中以连续的方式存储元素,因此访问任意位置的元素非常高效(时间复杂度为 O(1))。然而,当需要插入或删除中间元素时,可能需要移动大量元素以保持连续性,这会导致较高的时间开销(时间复杂度为 O(n))。 - **双向链表** 双向链表由节点组成,每个节点包含数据部分和两个指针,分别指向其前驱节点和后继节点[^1]。这种结构使得双向链表在插入和删除操作上表现优异(时间复杂度为 O(1),前提是已知目标节点的位置),但在随机访问元素时效率较低(时间复杂度为 O(n)),因为需要从头或尾逐个遍历节点。 #### 2. 区别 - **存储方式** 动态数组在内存中以连续的方式存储元素,而双向链表的节点可以分散存储在内存的不同位置,通过指针相互连接[^4]。这意味着动态数组更适合于内存分配固定的场景,而双向链表则更适合于内存需求动态变化的场景。 - **访问效率** 动态数组支持随机访问,可以通过索引直接定位到任意元素,时间复杂度为 O(1)[^2]。而双向链表不支持随机访问,必须从头或尾开始逐个遍历节点,时间复杂度为 O(n)[^1]。 - **插入与删除效率** 在动态数组中,插入或删除中间元素需要移动大量元素以保持连续性,时间复杂度为 O(n)[^2]。而在双向链表中,插入或删除操作只需修改相关节点的指针,时间复杂度为 O(1)(前提是已知目标节点的位置)[^1]。 - **内存开销** 动态数组的内存开销较低,因为它只需要存储数据本身。而双向链表的每个节点除了存储数据外,还需要额外存储两个指针,因此内存开销较大。 #### 3. 使用场景 - **动态数组** - 当需要频繁进行随机访问操作时,动态数组是更好的选择[^2]。 - 当数据规模相对固定或增长缓慢时,动态数组能够提供更高的空间利用率和访问效率。 - 示例:实现缓存系统、存储静态数据集合等。 - **双向链表** - 当需要频繁进行插入和删除操作时,双向链表更为合适。 - 当数据规模动态变化较大且无法提前预估时,双向链表能够更灵活地管理内存[^4]。 - 示例:实现队列、栈、LRU 缓存等。 ### 示例代码 以下是一个简单的动态数组双向链表的对比示例: ```java // 动态数组示例 import java.util.ArrayList; public class DynamicArrayExample { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); System.out.println(list.get(0)); // 随机访问,时间复杂度 O(1) } } // 双向链表示例 import java.util.LinkedList; public class DoublyLinkedListExample { public static void main(String[] args) { LinkedList<Integer> list = new LinkedList<>(); list.add(1); list.add(2); list.removeFirst(); // 删除第一个元素,时间复杂度 O(1) System.out.println(list.getFirst()); // 访问第一个元素,时间复杂度 O(1) } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值