70ptsTLEon#8#9#10,手写链表
查看原帖
70ptsTLEon#8#9#10,手写链表
891606
2023gdgz01楼主2023/6/28 19:18

本蒟看不懂题解啊,只会暴力,有什么优化方法

#include <cstdio>

using namespace std;

struct node
{
	node *prev, *next;
	int data, id;
};//基本双向链表 

int n, type, cur, fruit[200005];//fruit:果篮里水果编号 
node *head = new node, *tail = new node, *p, *last;//head:链头tail:链尾 

int main()
{
	head->prev = NULL;
	head->next = tail;
	tail->prev = head;
	tail->next = NULL;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		scanf("%d", &type);
		p = new node;//后插p 
		p->data = type;
		p->id = i;
		tail->prev->next = p;
		p->prev = tail->prev;
		p->next = tail;
		tail->prev = p;
	}
	while (head->next != tail)
	{
		p = last = new node;
		cur = 0;
		last = head->next;//将删除的元素 
		p = last->next;//遍历链表 
		while (p != tail)
		{
			if (p->data != last->data) 
			{
				cur++;
				fruit[cur] = last->id;
				last->next->prev = last->prev;//删除last 
				last->prev->next = last->next;//删除last 
				last = p;//更新标记 
			}
			p = p->next;//遍历 
		}
		cur++;//更新最后一"块" 
		fruit[cur] = last->id;
		last->next->prev = last->prev;
		last->prev->next = last->next;
		for (int i = 1; i <= cur; i++)
		{
			printf("%d ", fruit[i]);
		}
		printf("\n");
	}//TTTTTLLLLLEEEEE 
	return 0;
}
2023/6/28 19:18
加载中...