1. 程式人生 > >hdu-多校聯賽6301 Distinct Values

hdu-多校聯賽6301 Distinct Values

題目連結

Problem Description

Chiaki has an array of n positive integers. You are told some facts about the array: for every two elements ai and aj in the subarray al..r (l≤i<j≤r), ai≠ajholds.
Chiaki would like to find a lexicographically minimal array which meets the facts.

Input

There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:

The first line contains two integers n and m (1≤n,m≤105) -- the length of the array and the number of facts. Each of the next m lines contains two integers li and ri (1≤li≤ri≤n).

It is guaranteed that neither the sum of all n nor the sum of all m exceeds 106.

Output

For each test case, output n integers denoting the lexicographically minimal array. Integers should be separated by a single space, and no extra spaces are allowed at the end of lines.

Sample Input

3

2 1

1 2

4 2

1 2

3 4

5 2

1 3

2 4

Sample Output

1 2

1 2 1 2

1 2 3 1 1

題目大意:

輸入一個T,表示T組測試樣例;再輸入n,m表示一共n個數,m個區間。每個區間內的數不能相同,最小為1,整數增加。

輸出總和最小的數列。

大體思路:

pre陣列記錄每個區間,陣列下標代表區間末端,陣列記憶體的是區間前端;flag當做判斷指標;將區間前的數全部返回到set內(自動排序),a陣列存最終答案;(程式碼內詳細解釋)

程式碼:

#include<bits/stdc++.h>
using namespace std;
int pre[1000005],a[1000005];
int main()
{
    int t,n,m,l,r;
    scanf("%d",&t);
    while(t --)
    {
        scanf("%d%d",&n,&m);
        for( int i = 1;i <= n;i ++) pre[i] = i;
        while(m --)
        {
            scanf("%d %d",&l,&r);
            pre[r] = min(pre[r],l);//記錄區間的左端點(r代表末端點,pre陣列記憶體的數代表左端點)
        }
        for(int i = n-1;i >= 1;i --)
            pre[i] = min(pre[i],pre[i+1]);//
        set<int> s;//插入後自動預設從小到大排序
        for(int i = 1;i <= n;i ++)
        {
            s.insert(i);//賦初值
        }
        int flag = 1;
        for(int i = 1;i <= n;i ++)
        {
            while(flag < pre[i])//將這個區間前的數全部返回
            {
                s.insert( a[flag]);//新增
                flag++;
            }
            a[i] = *s.begin();//a呼叫set內最小的數
            s.erase(a[i]);//存到a陣列後就刪除
        }
        for( int i = 1;i < n;i ++)
            printf("%d ",a[i]);
        printf("%d\n",a[n]);
    }

}