Boxes in a Line UVA - 12657 (双向链表+数组实现)
发布日期:2021-06-21 09:00:14 浏览次数:3 分类:技术文章

本文共 1542 字,大约阅读时间需要 5 分钟。

题目:

对一行数组有四种操作:

1.把数字x放到数字y的左边

2.把数子X放到数字Y的右边

3.交换X和Y的位置

4.把所有数字翻转顺序

思路:

如果用数组的话,明显第四个操作就会明显超时。所以采用链表。用链表模拟一下就行。此处采用数组模拟链表实现

对于第四种操作,可以用一个变量去判断是否翻转,如果翻转的话,只需要把原来的左右指针交换即可。

注意交换的时候,两个数字相邻和两个数字不相邻是两种不同的方式。

代码:

/*by kzl*/#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;const int maxx = 1e5+500;const int INF = 0x3f3f3f3f;typedef long long LL;int n,m,a,x,y;int lnext[maxx],rnext[maxx];long long sum = 0;void init(){ for(int i=1; i<=n; i++)rnext[i] = i+1,lnext[i] = i-1; rnext[0] = 1;lnext[0] = n;rnext[n] = 0; sum = 0;}void one(int l[],int r[],int x,int y){ if(l[y]==x)return; l[r[x]] = l[x]; //把X从列表中删除 r[l[x]] = r[x]; r[l[y]] = x;//将x插入到y左侧 l[x] = l[y]; r[x] = y; l[y] = x;}void two(int l[],int r[],int x,int y){ if(r[y]==x)return; l[r[x]] = l[x]; //把X从列表中删除 r[l[x]] = r[x]; //将x插入到y右侧 l[r[y]] = x; r[x] = r[y]; r[y] = x; l[x] = y;}void three(int l[],int r[],int x,int y){ if(r[y]==x)swap(x,y); if(r[x]==y){ r[x] = r[y]; l[r[y]] = x; l[y] = l[x]; r[l[x]] = y; r[y] = x; l[x] = y; return ; } int cc = r[x],dd = l[x]; l[r[y]] = x;r[l[y]] = x; r[x] = r[y];l[x] = l[y]; l[cc] = y;r[dd] = y; r[y] = cc;l[y] = dd;}void getsum(int ne[]){ for(int i = ne[0],j=1;i!=0;i = ne[i],j++){ if(j&1&&i<=n)sum+=i; }}int main(){ int num = 1; while(scanf("%d%d",&n,&m)!=EOF) { init(); int flag = 0; for(int i=0; i

可优化:

以上代码可以有以下优化:

1.连接两个节点的操作可以写成一个函数,节省代码。

2.对于4操作,因为因为他只影响了1,2的顺序,而且1,2操作相对来说正好关于4操作对称,所以翻转之后的1操作实际就是之前的2操作。而不必要翻转指针。

转载地址:https://blog.csdn.net/lwgkzl/article/details/82788822 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Broken Keyboard (a.k.a. Beiju Text) UVA - 11988(链表模拟,数组实现,紫书代码注释)
下一篇:CSU - 1581 Clock Pictures(简单KMP)

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月10日 11时15分43秒