数学链表

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic Discuss

Problem Description

Fish 得到了一个神奇的数学链表,链表上每个节点有一个值,并且想要往这个链表中插入数据。

但是这个是一个很神奇的数学链表,插入的时候有一个特定的规则,插入时给出一个 x 和 k,让当前链表所有值为 x 和 x 的倍数的节点后面插入一个新节点值为 k,如果没有这样的节点,那么在链表尾部插入一个节点,值为 k。

(保证最后形成的链表不超过 10000 个节点)

Input

多组输入:

    每组第一行输入一个整数 n,和 m,代表初始的链表长度为 n,接下来有 m 次插入操作。(1 <= n <= 100, 1 <= m <= 10000)

    第二行输入 n 个正整数,以空格隔开。(节点的值为不超过 1000 的正整数)

    接下来 m 行,每行一个 x 和 k,含义如上。(1 <= x, k <= 1000)

Output

输出最终形成的链表。

Sample Input

5 3
1 2 3 4 5
1 6
3 2
9 9
5 5
720 830 871 503 490
854 162
579 830
724 271
508 596
519 88

Sample Output

1 6 2 2 6 2 3 2 6 2 4 6 2 5 6 2 9
720 830 871 503 490 162 830 271 596 88

Hint

Source

Fish

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};
int main()
{
    struct node *head, *p, *tail, *q;
    int n, m, i, x, k;
    while(scanf("%d%d", &n, &m) != EOF)
    {
        head = (struct node *)malloc(sizeof(struct node));
        head->next = NULL;
        tail = head;
        for(i = 1; i <= n; i++)
        {
            p = (struct node *)malloc(sizeof(struct node));
            scanf("%d", &p->data);
            p->next = NULL;
            tail->next = p;
            tail = p;
        }
        for(i = 1; i <= m; i++)
        {
            scanf("%d%d", &x, &k);
            int flag = 1;
            for(p = head->next; p->next != NULL; p = p->next)
            {
                if(p->data % x == 0)
                {
                    q = (struct node *)malloc(sizeof(struct node));
                    q->data = k;
                    q->next = p->next;
                    p->next = q;
                    flag = 0;
                    p = p->next;
                }
            }
            if(p->data % x == 0)
            {
                q = (struct node *)malloc(sizeof(struct node));
                q->data = k;
                q->next = p->next;
                p->next = q;
                flag = 0;
                p = p->next;
            }
            if(flag == 1)
            {
                q = (struct node *)malloc(sizeof(struct node));
                q->data = k;
                q->next = NULL;
                p->next = q;
            }
        }
        for(p = head->next; p->next != NULL; p = p->next)
        {
            printf("%d ", p->data);
        }
        printf("%d\n", p->data);
    }
    return 0;
}