ZOJ4102 Array in the Pocket(2019浙江省赛)

贪心~

#include<bits/stdc++.h>
using namespace std;
const int maxn=100014;
int a[maxn];
int b[maxn];
int vis[maxn];
set<int>s;
set<int>::iterator it;
vector<int>va[maxn],vb[maxn];
vector<int>v1,v2;
int main()
{
    int T;
    scanf ("%d",&T);
    while (T--) {
        int n;
        bool flag=true;
        scanf ("%d",&n);
        for (int i=1;i<=n;i++) {
            scanf("%d",&a[i]);
            vis[a[i]]++;
            if(vis[a[i]]>n/2) flag=false;
            s.insert(a[i]);
        }
        if(flag) {
            for(int i=1;i<=n;i++) {
                it=s.begin();
                if(*it==a[i]&&s.size()==1) {
                    for(int j=i+1;j<=n;j++)
                    if(a[j]!=a[i]) {
                        b[j]=a[i];
                        vis[a[i]]--;
                    }
                    for(int j=i;j<=n;j++)
                    if(a[j]==a[i]&&b[j]==0) v1.push_back(j);
                    for(int j=i-1;j>=1;j--) {
                        if(vis[a[i]]==0) break;
                        if(a[j]!=a[i]&&b[j]!=a[i]) {
                            v2.push_back(b[j]);
                            b[j]=a[i];
                            vis[a[i]]--;
                        }
                    }
                    s.erase((*it));
                    sort(v1.begin(),v1.end());
                    sort(v2.begin(),v2.end());
                    for(int i=0;i<v1.size();i++) b[v1[i]]=v2[i];
                    v1.clear();v2.clear();
                    break;
                }
                else {
                    if(*it==a[i])
                        it++;
                    b[i]=(*it);
                    vis[*it]--;
                    if(vis[*it]==0)
                        s.erase(*it);
                }
            }
            for(int i=1;i<=n;i++) va[a[i]].push_back(i),vb[a[i]].push_back(b[i]);
            for(int i=1;i<=n;i++) {
                sort(va[a[i]].begin(),va[a[i]].end());
                sort(vb[a[i]].begin(),vb[a[i]].end());
                for(int j=0;j<va[a[i]].size();j++)
                    b[va[a[i]][j]]=vb[a[i]][j];
                va[a[i]].clear();
                vb[a[i]].clear();
            }
            for(int i=1;i<=n;i++) printf(i==n?"%d\n":"%d ",b[i]);
        }
        else printf("Impossible\n");
        for(int i=1;i<=n;i++) vis[i]=0,b[i]=0;
        s.clear();
    }
    return 0;
}

 

posted @ 2020-02-13 14:37  zlc0405  阅读(270)  评论(0编辑  收藏  举报