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 lizimeng at 2016-08-06 17:16:17 on Problem 3069
想一想很好做。对数据排序,然后从一段开始找,要能包住所有的点,然后尽量少。
代码如下:
#include <stdio.h>
#include <stdlib.h>

void q_sort(int *a,int s,int t)
{
    int i, j;
    if(s<t)
    {
        i = s+1;
        j = t;
        while(1)
        {
            while(i<=t && a[i]<=a[s])
                i++;

            while(j>s && a[j]>=a[s])
                j--;

            if(i>=j)
                break;

            a[i] ^= a[j];
            a[j] ^= a[i];
            a[i] ^= a[j];
        }
        if(j!=s)
        {
            a[s] ^= a[j];
            a[j] ^= a[s];
            a[s] ^= a[j];
        }
        q_sort(a, s, j-1);
        q_sort(a, j+1, t);
    }
}

int main()
{
    int r, n, i, a[1000], C, R, mark;

    scanf("%d%d", &r, &n);
    while(!(r==-1 && n==-1))
    {
        for(i=0;i<n;i++)
        {
            scanf("%d", a+i);
        }

        q_sort(a, 0, n-1);

        //printf("111\n");

        mark = 0;
        i = 0;
        while(1)
        {
            C = a[i] + r;
            while(i<n && a[i] <= C)
                i++;
            mark++;
            if(i>=n)
                break;

            R = a[i-1] + r;
            while(i<n && a[i]<=R)
                i++;
            if(i>=n)
                break;
        }

        printf("%d\n", mark);

        scanf("%d%d", &r, &n);
    }

    return 0;
}

《挑战程序设计竞赛》第二版的贪心算法这一章有讲到这个题。这本书不错,如果学竞赛的话,我觉得比《算法导论》更实用一些。可以入手哦。电子版应该也很容易找到。

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