一个很经典的题目,HNU OJ 的链接是 http://acm.hnu.cn/online/?action=problem&type=show&id=13274 点击打开链接
CF上面似乎也有这一题,没专门去找
Inversion Sequence |
Time Limit: 2000ms, Special Time Limit:5000ms,Memory Limit:65536KB |
Total submit users: 13, Accepted users:8 |
Problem 13274 : No special judgement |
Problem 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. |
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 |
题意:有n大的数组,但是,只知道每个数前面有多少个数字比它大(即与它相关,在它之前的,逆序数对数),要你还原数组
两种思路
1.vector vector.insert的使用简直就是为这题专门而做,v.insert(地址***,i),在地址***的前面插入一个i,后面的直接后移
#include<cstdio>
#include<vector>
using namespace std;
int main()
{
int n;
while(~scanf("%d",&n))
{
int q[10005]={-1},flag=1;
for(int i=1;i<=n;i++) scanf("%d",&q[i]); //储存每个数字的逆序数信息
vector<int>v;
for(int i=n;i>=1;i--){ //从大到小往v里面插入
if(v.size()<q[i]){flag=0;break;} //不会有的情况
v.insert(v.begin()+q[i],i); //插入
}
if(flag){
for(int i=0;i<n-1;i++) //输出
printf("%d ",v[i]);
printf("%d\n",v[n-1]);
}
else puts("No solution");
}
return 0;
}
2. 线段树找空位置插入。。(该想法并非原创,感谢大神http://www.cnblogs.com/crackpotisback/p/4379405.html)
#include <bits/stdc++.h>
using namespace std;
const int maxn = 10010;
struct node {
int lt,rt,pos;
} tree[maxn<<2];
int d[maxn],ans[maxn],n;
bool flag;
void build(int lt,int rt,int v) {
tree[v].lt = lt;
tree[v].rt = rt;
if(lt == rt) {
tree[v].pos = 1;
return;
}
int mid = (lt + rt)>>1;
build(lt,mid,v<<1);
build(mid+1,rt,v<<1|1);
tree[v].pos = tree[v<<1].pos + tree[v<<1|1].pos;
}
void update(int s,int v,int value) {
if(tree[v].lt == tree[v].rt) {
tree[v].pos = 0;
ans[tree[v].lt] = value;
return;
}
if(tree[v<<1].pos >= s) update(s,v<<1,value);
else if(tree[v<<1|1].pos >= s - tree[v<<1].pos) update(s-tree[v<<1].pos,v<<1|1,value);
else flag = false;
tree[v].pos = tree[v<<1].pos + tree[v<<1|1].pos;
}
int main() {
while(~scanf("%d",&n)) {
build(1,n,1);
flag = true;
for(int i = 1; i <= n; ++i) {
scanf("%d",d+i);
if(flag) update(d[i]+1,1,i);
}
if(flag) for(int i = 1; i <= n; ++i)
printf("%d%c",ans[i],i == n?'\n':' ');
else puts("No solution");
}
return 0;
}