POJ2182(排队问题)
阅读原文时间:2023年07月09日阅读:1

Lost Cows

Time Limit: 1000MS

 

Memory Limit: 65536K

Total Submissions: 10695

 

Accepted: 6865


Description

N (2 <= N <= 8,000) cows have unique brands in the range 1..N. In a spectacular display of poor judgment, they visited the neighborhood 'watering hole' and drank a few too many beers before dinner. When it was time to line up for their evening meal, they did not line up in the required ascending numerical order of their brands.

Regrettably, FJ does not have a way to sort them. Furthermore, he's not very good at observing problems. Instead of writing down each cow's brand, he determined a rather silly statistic: For each cow in line, he knows the number of cows that precede that cow in line that do, in fact, have smaller brands than that cow.

Given this data, tell FJ the exact ordering of the cows.

Input

* Line 1: A single integer, N

* Lines 2..N: These N-1 lines describe the number of cows that precede a given cow in line and have brands smaller than that cow. Of course, no cows precede the first cow in line, so she is not listed. Line 2 of the input describes the number of preceding cows whose brands are smaller than the cow in slot #2; line 3 describes the number of preceding cows whose brands are smaller than the cow in slot #3; and so on.

Output

* Lines 1..N: Each of the N lines of output tells the brand of a cow in line. Line #1 of the output tells the brand of the first cow in line; line 2 tells the brand of the second cow; and so on.

Sample Input

5
1
2
1
0

Sample Output

2
4
5
3
1
题意:
第一行给出cow的数目n,接下来2-n行给出每个排在第2-n各位置的cow的在其编号比其小的个数。最后按排队顺序依次给出每个cow的编号。
思路:
从后向前确定编号,设比最后一个cow小的cow数目为a,则最后一个cow的编号为所剩下cow 的第(a+1)大编号。

#include"cstdio"
#include"cstring"
#include"algorithm"
using namespace std;
const int MAXN=;
int n;
int deg[MAXN];
int vis[MAXN];
int ans[MAXN];
int seek(int k)
{
int pos=;
for(int i=;i<=n;i++) { if(!vis[i]) { pos++; if(pos==k) return i; } } } int main() { while(scanf("%d",&n)!=EOF) { memset(vis,,sizeof(vis)); deg[]=; for(int i=;i=;i--)
{
int pos=seek(deg[i]+);
vis[pos]=;
ans[i]=pos;
}
for(int i=;i<n;i++)
{
printf("%d\n",ans[i]);
}

}

return ;  

}

转化为排队问题,利用线段树求解.

#include"cstdio"
#include"cstring"
#include"algorithm"
using namespace std;
const int MAXN=;
struct node{
int l,r;
int n;
}a[MAXN*];
int que[MAXN];
int pos[MAXN];
void build(int rt,int l,int r)
{
a[rt].l=l;
a[rt].r=r;
a[rt].n=(r-l+);
if(l==r) return;
int mid=(l+r)>>;
build(rt<<,l,mid);
build((rt<<)|,mid+,r);
}

void update(int rt,int pos,int i)
{
if(a[rt].l==a[rt].r)
{
a[rt].n--;
que[i]=a[rt].l;
return ;
}

if(pos<=a\[rt<<\].n)    update(rt<<,pos,i);  
else update((rt<<)|,pos-a\[rt<<\].n,i);  
a\[rt\].n=a\[rt<<\].n+a\[(rt<<)|\].n;  

}

int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
build(,,n);
pos[]=;
for(int i=;i=;i--)
{
update(,pos[i]+,i);
}
for(int i=;i<n;i++)
{
printf("%d\n",que[i]);
}
}

return ;  

}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章