Problem Description
我们定义素数链表为元素全部是素数的链表。
给定一个初始含有 n 个元素的链表,并给出 q 次删除操作,对于每次操作,你需要判断链表中指定位置上的元素,如果元素存在且不是素数则删除。
在所有操作完成后你还需要检查一下最终链表是否是一个素数链表。
Input
输入数据有多组。第 1 行输入 1 个整数 T (1 <= T <= 25) 表示数据组数。
对于每组数据:
- 第 1 行输入 2 个整数 n (1 <= n <= 50000), q (1 <= q <= 1000) 表示链表初始元素数量和操作次数
- 第 2 行输入 n 个用空格隔开的整数(范围 [0, 1000])表示初始链表
- 接下来 q 行,每行输入 1 个整数 i (1 <= i <= 50000),表示试图删除链表中第 i 个元素
Output
对于每组数据:
- 先输出 1 行 "#c",其中 c 表示当前是第几组数据
- 对于每次删除操作,根据情况输出 1 行:
- 如果要删除的位置不存在元素(位置超出链表长度),则输出 "Invalid Operation"
- 如果要删除的位置存在元素且此位置的元素是非素数,则删除元素并输出 "Deleted x",其中 x 为成功删除的数(必须为非素数才能删除)
- 如果要删除的位置存在元素且此位置的元素是素数,则输出 "Failed to delete x",其中 x 为此位置上的数
- 删除操作全部进行完毕后,则还需判断该链表现在是否为一个素数链表。如果链表非空且是素数链表,则输出 "All Completed. It's a Prime Linked List",否则输出 "All Completed. It's not a Prime Linked List"
所有输出均不包括引号。
Example Input
2 1 2 0 5 1 6 3 1 2 3 3 4 5 1 1 4
Example Output
#1 Invalid Operation Deleted 0 All Completed. It's not a Prime Linked List #2 Deleted 1 Failed to delete 2 Deleted 4 All Completed. It's a Prime Linked List
Hint
推荐直接复制粘贴输出语句字符串到你的代码中,以防手打敲错。
链表中第 1 个元素的位置为 1,第 2 个元素的位置为 2,以此类推。
Author
「2016级《程序设计基础(B)II》期末上机考试-第一场」bLue
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
struct node
{
int data;
struct node *next;
};
int supan(int n) //判断输入的数是否为素数 ,为了能够提高效率,一般判断素数的使用方法为开平方发sqrt;
{
int i;
int flag=1;
for(i=2; i<=sqrt(n); i++)
{
if(n%i==0)
flag=0;
}
if(flag)
return 1;
else
return 0;
}
struct node*creat(int n)
{
struct node *head,*tail,*p;
int i;
head=(struct node *)malloc(sizeof(struct node ));
head->next=NULL;
tail=head;
for(i=0; i<n; i++)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;
tail->next=p;
tail=p;
}
return head;
}
void find(struct node *head,int m,int n)
{
struct node *p,*q;
int k;
int i;
int flag=1;
while(m--)
{
scanf("%d",&k);
if(k>n)
printf("Invalid Operation\n");
else
{
p=head;
for(i=1; i<k; i++)
p=p->next;
q=p->next;
if(q->data==1||q->data==0||(q->data>2&&supan(q->data)==0))
{
printf("Deleted %d\n",q->data);
p->next=q->next;
free(q);
n--;
}
else if(q->data==2||(q->data>2&&supan(q->data)==1))
{
printf("Failed to delete %d\n",q->data);
}
}
}
p=head->next;
while(p!=NULL) //当输入关键字完毕时,需要遍历剩余的链表上的元素,是否存在素数
{
if((p->data==1||p->data==0)||(p->data>2&&supan(p->data)==0))
{
flag=0;
break;
}
p=p->next;
}
if(flag==1&&n>0)
printf("All Completed. It's a Prime Linked List\n");
else
printf("All Completed. It's not a Prime Linked List\n");
}
int main()
{
int n;
int m;
int t;
struct node *head;
int i=1;
scanf("%d",&t);
while(t--)
{
printf("#%d\n",i);
scanf("%d %d",&n,&m);
head=creat(n);
find(head,m,n);
i++;
}
return 0;
}