zoukankan      html  css  js  c++  java
  • 顺序表应用4-2:元素位置互换之逆置算法(数据改进)(SDUT 3663)

    Problem Description

    一个长度为len(1<=len<=1000000)的顺序表,数据元素的类型为整型,将该表分成两半,前一半有m个元素,后一半有len-m个元素(1<=m<=len),设计一个时间复杂度为O(N)、空间复杂度为O(1)的算法,改变原来的顺序表,把顺序表中原来在前的m个元素放到表的后段,后len-m个元素放到表的前段。
    注意:交换操作会有多次,每次交换都是在上次交换完成后的顺序表中进行。

    Input

    第一行输入整数len(1<=len<=1000000),表示顺序表元素的总数;

    第二行输入len个整数,作为表里依次存放的数据元素;

    第三行输入整数t(1<=t<=30),表示之后要完成t次交换,每次均是在上次交换完成后的顺序表基础上实现新的交换;

    之后t行,每行输入一个整数m(1<=m<=len),代表本次交换要以上次交换完成后的顺序表为基础,实现前m个元素与后len-m个元素的交换;

    Output

    输出一共t行,每行依次输出本次交换完成后顺序表里所有元素。

    Sample Input

    10
    1 2 3 4 5 6 7 8 9 -1
    3
    2
    3
    5

    Sample Output

    3 4 5 6 7 8 9 -1 1 2
    6 7 8 9 -1 1 2 3 4 5
    1 2 3 4 5 6 7 8 9 -1

    题解:设计的时间复杂度为O(n),所以可以先把整个表都逆置,然后把前m个和后len-m个分别再逆置一次。

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    const int maxn = 1000000;
    struct node
    {
        int *elem;
        int len;
    };
    
    void Creatlist(int len, struct node &list)
    {
        list.elem = (int *)malloc(maxn*sizeof(int));
        list.len = len;
        for(int i = 0; i < len; i ++)
        {
            scanf("%d",&list.elem[i]);
        }
    }
    void Move(int front,int end,struct node &list)
    {
        for(int i = front,j = 0; i < (front + end + 1) / 2; i ++, j ++)
        {
            int x = list.elem[i];
            list.elem[i] = list.elem[end - j - 1];
            list.elem[end - j - 1] = x;
        }
    }
    void print(struct node &list)
    {
        for(int i = 0; i < list.len - 1; i ++)
            printf("%d ",list.elem[i]);
        printf("%d
    ",list.elem[list.len-1]);
    }
    int main()
    {
        int len,t,m;
        struct node list;
        scanf("%d",&len);
        Creatlist(len,list);
        scanf("%d",&t);
        while(t--)
        {
            scanf("%d",&m);
            Move(0,len,list);
            Move(0,len - m, list);
            Move(len - m,len,list);
            print(list);
        }
        return 0;
    }
    

    (图片来源百度)

  • 相关阅读:
    Study Plan The Twelfth Day
    Study Plan The Fifteenth Day
    Study Plan The Seventeenth Day
    Study Plan The Tenth Day
    Study Plan The Eighth Day
    Study Plan The Eleventh Day
    Study Plan The Sixteenth Day
    Study Plan The Thirteenth Day
    Study Plan The Fourteenth Day
    Study Plan The Ninth Day
  • 原文地址:https://www.cnblogs.com/lcchy/p/10139557.html
Copyright © 2011-2022 走看看