POJ 2182 Lost Cows(树状数组,暴力解法)
2014年03月20日 02:00:55 阅读数:1938 标签: ACM 更多
个人分类: 数据结构--树状数组ACM--题解汇总★★ACM--技巧题practice again
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013480600/article/details/21574467
POJ 2182 Lost Cows(树状数组,暴力解法)
http://poj.org/problem?id=2182
题意:
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
分析:
其实这道题目只要会手算用例就能暴力解决。
假设读入题目给的数组a[n],其中a[1]=0
这道题目只给出了在i之前且比位于第i个位置的值小的值有多少个,我们在纸上分析用例可知,最后一个数的值肯定是a[n]+1.
然后我们从后往前推,且初始化一个数组vis[n]为全1。vis[i]==1表示当前值为i的数还没出现。首先我们推出最后一个数的值为a[n]+1,所以我们标记vis[a[n]+1]=0,接着我们推n-1的值,假设a[n-1]=3,那么就是在n-1的数之前有3个还未出现的数比它小,那么我们从vis[1]开始扫描,找到第4个1的位置就是a[n-1]的值。然后把这第4个1的位置vis[x]标记0.接下去找n-2位置的值,以此类推即可。
<span style="font-size:18px;">#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN =10000;
int a[MAXN];//初始
int vis[MAXN];//标记1
int ans[MAXN];//最终计算的结果
int main()
{
int n;
while(scanf("%d",&n)==1&&n)
{
a[1]=0;
for(int i=2;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<=n;i++)
vis[i]=1;
ans[n]=a[n]+1;
vis[ans[n]]=0;
for(int i=n-1;i>=1;i--)
{
int num = a[i];
int j;
for(j=1;i<=n;j++)
{
if(vis[j]==1)
{
num--;
if(num<0)
{
vis[j]=0;
break;
}
}
}
ans[i]=j;
}
for(int i=1;i<=n;i++)
printf("%d\n",ans[i]);
}
return 0;
}</span>