Lost Cows POJ 2182 law clever thinking +

Lost Cows POJ 2182 thinking

The meaning of problems

N is said to have cows, their height vary but lined up a team, from left to right are numbered from 1 to n, and now tell you from the start in front of the second number is less than the height of the cattle in its number, a total of n-1 number. Then find them sorted according to height, then from low to high numbers would be.

Problem-solving ideas

First, we need to from it to the data reverse process, why, for example, the penultimate data is 0, it indicates that the front is not shorter than its cattle, its number is 1, then the penultimate is 2, then, that there are two front than it short, because No. 1 already, so he is No. 4, behind and so on.

According to this idea we can simulate (or violence to resolve), of course, you can use the segment tree or tree-like array to be optimized.

There is also an algorithm is based on the bubble sort, is hxr brother thought, really tql.

Code

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=8e5+7;
int a[maxn], vis[maxn];
int n;
int main()
{
    scanf("%d", &n);
    for(int i=2; i<=n; i++)
    {
        scanf("%d", &a[i]);
    }
    int t;
    for(int i=n; i>=1; i--)
    {
        t=a[i]+1;
        for(int j=1; j<=t; j++) //这是在剩下的数中查找第t小的数
        {
            if(vis[j]==1)
                t++;
        }
        a[i]=t;
        vis[t]=1;
    }
    for(int i=1; i<=n; i++)
    {
        printf("%d\n", a[i]);
    }
    return 0;
 } 

Bubble sort

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream> 
using namespace std;
const int maxn=8e3+7;
int a[maxn], id[maxn];
int num[maxn];
int n;
int main()
{
    cin>>n;
    a[1]=0;
    id[1]=1;
    for(int i=2; i<=n; i++)
    {
        cin>>a[i];
        id[i]=i;
    }
    for(int j=1; j<n; j++)
    {
        for(int i=1; i<n; i++)
        {
            if(a[i]>=a[i+1])
            {
                a[i]++;
                swap(a[i], a[i+1] );
                swap(id[i], id[i+1]);
                //for(int t=1; t<=n; t++) cout<<a[t]<<" "; cout<<"\n";
                //for(int t=1; t<=n; t++) cout<<id[t]<<" "; cout<<"\n";
                //system("pause");
            }
            
        }
    }
    for(int i=1; i<=n; i++)
        num[id[i]]=i;
    for(int i=1; i<=n; i++)
    {
        cout<<num[i]<<endl;
    }
    
    return 0;
 } 

Guess you like

Origin www.cnblogs.com/alking1001/p/11415748.html