Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

谁帮我看看思路(最小堆)

Posted by TYplayIT at 2011-12-02 11:10:38 on Problem 2051
输入完num和period之后建立最小堆,
然后每次输出堆顶,
并把堆中所有的元素的period减掉堆顶当前的period,
删掉堆顶,
恢复堆顶的period为输入时的period,重新添加进堆
直到输出k个

一直WA,我写了个暴力AC了,自己测试的时候两个程序的结果一样

代码:


#include<iostream>

using namespace std;

typedef struct
{
    int num;
    int p, op;
}Ins;

void MakeHeap(Ins a[], int n);
void addIns(Ins a[], int n, Ins b);
void FixUp(Ins a[],int i, int n);

Ins deleteIns(Ins a[], int n);
void FixDown(Ins a[], int i, int n);
void swap(Ins &a, Ins &b);

int main()
{
    char input[20];
    Ins a[2020];
    int n;
    int i = 0;
    while( cin >> input)
    {
        if(input[0] == '#')
        {
            break;
        }
        cin >> a[i].num >> a[i].p;
        a[i].op = a[i].p;
        i++;
    }

    cin >> n;

    MakeHeap(a, i);
    Ins temp;
    for(int j = 0; j < n; j++)
    {
        temp = deleteIns(a, i);
        for(int k = 0; k < i-1; k++)
        {
            a[k].p -= temp.p;
        }
        cout << temp.num << endl;
        temp.p = temp.op;
        addIns(a, i-1, temp);
    }
    return 0;
}

void MakeHeap(Ins a[], int n)       //n为数组个数
{
    for(int i = n/2-1; i > -1; i--)
    {
        FixDown(a, i, n);
    }
}
void addIns(Ins a[], int n, Ins b)      //n为添加前数组个数
{
    a[n] = b;
    FixUp(a, n, n+1);
}
void FixUp(Ins a[],int i, int n)        //i为新添加元素的位置,n为当前数组个数
{
    for(; i > 0; i /= 2)
    {
        if(a[i].p < a[i/2].p)
        {
            swap(a[i], a[i/2]);
        }
        else if(a[i].p == a[i/2].p)
        {
            if(a[i].num < a[i/2].num)
            {
                swap(a[i], a[i/2]);
            }
        }
    }
}
Ins deleteIns(Ins p[], int n)       //n为当前数组个数
{
    Ins temp = p[0];
    p[0] = p[n-1];
    FixDown(p, 0, n-1);
    return temp;
}
void FixDown(Ins a[], int i, int n)     //i为下移的元素位置,n为当前个数
{
    int j = i*2 +1;
    Ins temp = a[i];
    while( j < n)
    {
        if(j+1 < n)
        {
            if(a[j].p > a[j+1].p)
            {
                j++;
            }
            else if(a[j].p == a[j+1].p && a[j].num > a[j+1].num)
            {
                j++;
            }
        }
        if(a[j].p > temp.p)
        {
            break;
        }
        else if(a[j].p == temp.p && temp.num < a[j].num)
        {
            break;
        }
        a[i] = a[j];
        i = j;
        j = j * 2 +1;
    }
    a[i] = temp;
}
void swap(Ins &a, Ins &b)
{
    Ins temp = a;
    a = b;
    b = temp;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator