双向排序


import java.util.Arrays;
import java.util.Scanner;

public class 双向排序3 {


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();

        operation [] operations = new operation[m+1];

        int [] num = new int[n+1]; //从索引1开始
        int top = 0;

        for (int i = 1; i <= m; i++) {
            int p = sc.nextInt();

            int q = sc.nextInt();

/**
 * 9 5
 * 0 9
 * 1 2
 * 0 7
 * 1 4
 * 0 5
 */

            //降序数据
            if (p == 0) {
                while (top > 0 && operations[top].p == 0) {
                    q = Math.max(operations[top--].q, q);
                }


                while (top - 2 >= 0 && operations[top-1].q <= q) {
                    top -= 2;
                }

                operations[++top] = new operation(0, q);

            } else if (top != 0) {

                while (top > 0 && operations[top].p == 1) {
                    q = Math.min(operations[top--].q, q);

                }

                while (top - 2 >= 0 && operations[top - 1].q >= q) {
                    top -= 2;
                }

                operations[++top] = new operation(1, q);

            }





        }

//        System.out.println(Arrays.toString(operations));


        int k = n;
        int l = 1, r = n;

        for (int i = 1; i <= top; i++) {
            //降序操作,固定前面,添加后面
            if (operations[i].p == 0) {
                while (l <= r && r > operations[i].q) {
                    num[r--] = k--;
                }
//                System.out.println(operations[i]);
//                System.out.println(Arrays.toString(num));
            }else {
                //升序操作,固定后面,添加前面
                while (l <= r && l < operations[i].q) {
                    num[l++] = k--;
                }
//                System.out.println(operations[i]);
//                System.out.println(Arrays.toString(num));
            }

        }

        //发现中间还有没有填完的
         //如果最后一条是升序,则中间为升序操作
        if (operations[top].p == 1) {
            while (l <= r) {
                num[r--] = k--;

            }
        } else if (operations[top].p == 0) {
            while (l <= r) {
                num[l++] = k--;
            }
        }


        for (int i = 1; i <= n; i++) {
            System.out.print(num[i]+" ");
        }



    }









    static class operation{
        int p;
        int q;

        public operation(int p, int q) {
            this.p = p;
            this.q = q;
        }

        @Override
        public String toString() {
            return "operation{" +
                    "p=" + p +
                    ", q=" + q +
                    '}';
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值