sgu279:Bipermutations(貪心構造)

題目大意:
      ij 意味着在序列中i 的位置在j 的前面。
       構造一個長度爲2n 的序列,由1,1,2,2...,n,n 構成。
       滿足如下條件:
      1. 對於任意i 滿足ii
      2. 對於任意ij ,滿足ijij
      3. 定義bi,j={j,j<ij,j>iai=[ibi,j] ,給出序列a ,構造出滿足a 的序列。

分析:
       很顯然我們要倒着填。
      2n 位開始,每次找最小的i 使得ai=0 填在這一位,更新後面的a ,如果找不到,那就找位置最大的沒有填過ii 填在這一位,更新後面的a ,否則無解。
       爲什麼要先考慮ai=0 呢?設前者的結果爲c1 ,後者的結果爲c2 ,如果c2>c1c1 肯定在之前就被c2 給更新過,那麼兩者交換順序不影響;如果c2<c1 ,先放c2 肯定會使ac1 變小成負數,不符合題意,因此先考慮顯然可以。

AC code:

#include <cstdio>
#include <algorithm>
#define mp make_pair
#define pii pair<int,int>
#define x first
#define y second
#define debug(...) fprintf(stderr, __VA_ARGS__)
using namespace std;

const int MAXN = 1009;

int n;
short a[MAXN];
short ans[MAXN<<1];
short vis[MAXN];

int main()
{
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif

    scanf("%d", &n);
    for(int i = 1; i <= n; ++i)
        scanf("%d", a+i);

    for(int i = (n<<1); i >= 1; --i)
    {
        int c1 = -1, c2 = -1;
        for(int j = 1; j <= n; ++j)
            if(!a[j] && !vis[j])
            {
                c1 = j;
                break;
            }
        if(c1 != -1)
        {
            ans[i] = c1;
            vis[c1] = 1;
            for(int j = 1; j <= n; ++j)
                if(!vis[j] && j < c1)
                    --a[j];
        }
        else
        {
            for(int j = n*2; j > i; --j)
                if(ans[j] > 0 && vis[ans[j]] == 1)
                {
                    c2 = ans[j];
                    break;
                }
            if(c2 == -1)
            {
                puts("NO");
                return 0;
            }
            ans[i] = -c2;
            vis[c2] = 2;
            for(int j = 1; j <= n; ++j)
                if(!vis[j] && j > c2)
                    --a[j];
        }
    }

    puts("YES");
    for(int i = 1; i <= (n<<1); ++i)
        printf("%d ", ans[i]);
    puts("");

    #ifndef ONILNE_JUDGE
    fclose(stdin);
    fclose(stdout);
    #endif
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章