Description
For sequence i1, i2, i3, … , iN, we set aj to be the number of members in the sequence which are prior to j and greater to j at the same time. The sequence a1, a2, a3, … , aN is referred to as the inversion sequence of the original sequence (i1, i2, i3, … , iN). For example, sequence 1, 2, 0, 1, 0 is the inversion sequence of sequence 3, 1, 5, 2, 4. Your task is to find a full permutation of 1~N that is an original sequence of a given inversion sequence. If there is no permutation meets the conditions please output “No solution”.
Input
There are several test cases.
Each test case contains 1 positive integers N in the first line.(1 ≤ N ≤ 10000).
Followed in the next line is an inversion sequence a1, a2, a3, … , aN (0 ≤ aj < N)
The input will finish with the end of file.
Output
For each case, please output the permutation of 1~N in one line. If there is no permutation meets the conditions, please output “No solution”.
Sample Input
5 1 2 0 1 0 3 0 0 0 2 1 1
Sample Output
3 1 5 2 4 1 2 3 No solution
#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> #include <queue> using namespace std; #define INF 0x3f3f3f3f #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 typedef long long LL; const int maxn=10005; int sum[maxn<<2]; int pos,ok; int n; int k; int ans[maxn]; void pushup(int rt) { sum[rt]=sum[rt<<1]+sum[rt<<1|1]; } void build(int l,int r,int rt) { if(l==r) { sum[rt]=1; return; } int m=(l+r)>>1; build(lson); build(rson); pushup(rt); } void query(int t,int l,int r,int rt) { if(t>sum[rt]) { ok=0; return ; } if(l==r) { pos=l; sum[rt]=0; return ; } int m=(l+r)>>1; if(t<=sum[rt<<1]) query(t,lson); else query(t-sum[rt<<1],rson); pushup(rt); } int main() { //freopen("input.txt","r",stdin); while(~scanf("%d",&n)) { ok=1; build(1,n,1); for(int i=1; i<=n; i++) { scanf("%d",&k); if(!ok) continue; query(k+1,1,n,1); ans[pos]=i; } if(!ok) { printf("No solution "); continue; } printf("%d",ans[1]); for(int i=2;i<=n;i++) printf(" %d",ans[i]); printf(" "); } }
第二种方法是用vector数组来做
考虑到它能够插♂来♂插♂去♂的属性
#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> #include <queue> #include <vector> using namespace std; #define INF 0x3f3f3f3f #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 typedef long long LL; const int maxn=10005; int a[maxn]; vector<int> vec; int main() { //freopen("input.txt","r",stdin); int n; int k; while(~scanf("%d",&n)) { vec.clear(); for(int i=1; i<=n; i++) scanf("%d",&a[i]); int flag=1; for(int i=n; i>=1; i--) { if(vec.size()<a[i]) { flag=0; break; } vec.insert(vec.begin()+a[i],i); } if(flag) { for(int i=0; i<vec.size(); i++) { if(i!=0) printf(" "); printf("%d",vec[i]); } printf(" "); } else printf("No solution "); } }