CSP-homework Week3 ProblemA greed --- two questions point range selected issues and problems interval coverage (C ++)

Overview

Greedy algorithm is a commonly used method and portable, and are usually effective. This article describes two basic and classic problem of greed - Interval Interval choice of site problems and coverage issues, I hope some reading comprehension.

Topic one: the interval selected point problem

Original title description

With n closed interval [a_i, b_i] number line. Take as few points, such that have at least one point (point may be different sections containing the same) in each interval

INPUT

The first line of an integer N (N <= 100)
of 2 ~ N + 1 lines, each two integers a, b (a, b < = 100)

OUTPUT

An integer representing the number of selected points

SAMPLE INPUT

2
1 5
4 6

Sample Output

1

Title repeat

Meaning of the questions is relatively simple, given N intervals, each interval must ensure that there is at least one point, each selected point may exist in multiple sections, an attempt to satisfy this condition is determined how many such points need to pick.

Problem-solving ideas

Overview ideas

A classic greedy algorithm, greedy algorithm is the core problem is the greedy rules that determine the greedy rule will be able to easily solve the problem.
The title of the selected rule is sequentially selected greedyThe smallest range limitSequentially considered, there is no point if the upper limit will be selected within the interval section, until the entire interval is traversed.
The actual realization of ideas can probably be described as follows:
First, to maintain a map [] array to store each point is to be added too, is initialized to 0 for all points had not been added, in the course of the visit needs to be added is set to go on the 1.
Add a global variable

int number=0

Added as a dot counter, whenever a new point is added, the counter ++
intermediate greedy graph execution flow according to the following can be:

Created with Raphaël 2.2.0 对全部区间按照区间 上限值升序排序 访问区间中每个点 是否被添加过 map[]==1 该区间添加过点 访问下一个区间 yes no

If you have access to the range limit had yet to find a point to add, that this section needs to add a new point came in, in order to cover a larger selection of less-point range, as the choice of site selection range ceiling.
Upon completion of traversing the entire section of the counter value is the need to choose the number of points.

A topic summary

A relatively simple greedy algorithm topic, focusing on two aspects of the greedy strategy:
1, the order of traversal range - accessed using the upper range in ascending order according to the strategy, to ensure that there will be no interval is ignored, each section has at least a point.
2, the position of the selected point, - when a time interval not added point, add a new location of the point selected in the maximum range. In the process of backward traversal, the policy range ceiling point each addition to ensure the added point is minimal.

A source title

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int map[200];
int number=0;
struct time
{
    int a;
    int b;
    bool operator<(const time & ano)const
    {
        if(b!=ano.b) return b<ano.b;
        return a>ano.a;
    }
    void insert()
    {
        bool flag=true;
        for(int i=a;i<=b;i++)
        {
            if(map[i]==1)
            flag=false;
        }
        if(flag==true)
        {
            number++;
            map[b]=1;
        }
    }
};

int main()
{
    int all_number=0;
    cin>>all_number;
    int start=0;
    int end=0;
    time a[200];
    for(int i=0;i<200;i++)
    {
        map[i]=0;
    }
    for(int i=0;i<all_number;i++)
    {
        cin>>start>>end;
        a[i].a=start;
        a[i].b=end;
    }
    sort(a,a+all_number);
    for(int i=0;i<all_number;i++)
    {
        a[i].insert();
    }
    cout<<number<<endl;
    return 0;
}

Topic two: interval coverage problems

Original title description

There are a number line n (1 <= n <= 25000) a closed interval [ai, bi], selected to cover a range of as little as specified segment [1, t] (1 < = t <= 1,000,000).
Covering the entire point, i.e., (1,2) + (3,4) may cover (1,4).
The impossible Output -1

INPUT

First line: N T and the
second row N + 1 to row: each line a closed interval.

OUTPUT

Selected number of intervals, the output of the impossible -1

SAMPLE INPUT

3 10
1 7
3 6
6 10

Sample Output

2

Title repeat

The same problem faces easier to understand, given the range of use, choose the best strategy, covering the target range.
However, there are few data points to note, or easily given at some point in the process of solving:
1, the lower limit of the interval needed to cover 1 is fixed, closed interval.
2, objects to be covered between the sections used are closed interval, i.e., all the boundary points and the middle points are able to take, the subject described a comparison conscience error-prone situation

2 4
1 2
3 4

Description meaning of the title is closed interval and requires only cover the whole point is required as follows:
Here Insert Picture DescriptionIn the process of solving problems in the seek control attention and consideration to the boundary point, ensure that the code is still on.
3, the title is described in a fixed lower limit, the upper limit is equal to 1, that is it possible to cover the requirements [1], in this case 1 to be output is not 0.

Problem-solving ideas

Overview ideas

Understand the topic of some of the rules and pits selection interval can be determined greedy rule set out to design code.
First, the input process section, can be performed on certain points of the pretreatment, the convenience of description section will be referred to as an input [a, b], to be referred to as the target interval covers [A, B].
If the point a> B or b <B, then the input data is useless trash, discarded directly, this can ensure that data is present in a large amount of garbage to reduce the time of computation complexity.
In order to facilitate consideration of all the sections of the filtered data is sorted according to ascending order of the size of the upper section, to ensure that during traversal visits after completion of the sort, it must be at the top of the smallest range limit, it can be easily determined prior to A coverage zone can point.
Considering the meaning of problems to choose the least number of sections, the length L is introduced metrics are available to greedy algorithm.
[A, b] (b> A) for each available interval

L=b-A

The greedy strategy subject may be determined as: Select all interval, the maximum usable length L interval. Interval after once selected, will solve [A, B] into solving the problem coverage [b + 1, B] interval coverage problems.
If L (MAX)> BA, for the optional sections have been able to completely cover the target range, greedy ends and returns a sign of success covered;
if no L> 0 interval, the proof of this interval can not be overwritten, greedy ends , failure to return a sign of coverage.
Analysis shows the meaning of problems each time you select A is a fixed value, so you can select will be converted to L greedy greedy selection strategy b size. Design code needs to be noted that the upper and lower limits of the range of conversion.
Encapsulated codes are as follows:

int choose(int begin,int end)
{
    int cnt=0;
    int j=0;
    int flag=0;
    for(int i=0;i<room_number;i++)
    {
        int max_choose=-2e9;
        for(j=i;j<room_number && a[j].a<=begin;j++)
        {
            max_choose=max(max_choose,a[j].b);
        }
        if(max_choose<begin)
        {
            cnt=-1;
            break;
        }
        cnt++;
        if(max_choose>=end)
        {
        	flag=1;
            break;
        }
        i=j-1;
        begin=max_choose+1;
    }
    if(flag==1)
    return cnt;
    else
    return -1;
}

Topic two summary

Two questions reflect a greedy class of topics defining characteristics, surface simple questions, problems to be solved very clear, multiple sets of data to be processed, need to follow a certain strategy to be processed and traverse data.
Greedy algorithm from the classification strategy is the optimal solution for seeking part, the focus of its strategy to solve a greedy choice and proof. Choose a good and reasonable under the greedy strategy can guarantee low time complexity of premise and easily solve the problem.

Topic two points of improvement

In the learning process, an understanding of several pretreatment method, the general idea is as follows:
1, data preprocessing, for each segment, trim, leaving only needs to cover the effective portion between the interval [A, B], if the trim after the active portion does not exist, the delete section
2, the remaining section for greedy, the upper limit of the maximum time from the start of choice a, the following situations:

  • If a maximum range limit reached B, then it proves coverage ends and returns a sign of success.
  • If the number of the remaining interval is 0, and A! = B, instructions can not complete coverage, return a sign of failure.
  • If the remaining number range> 0, but can not find the start of the section A, the cover can not be described, a return flag failed.
  • If the section number> 0, and can find the start of the section A, the upper limit of the maximum upper limit thereof selection is b, is converted to the interval
    [b, B] interval coverage problems, repeat steps 1 and 2 to find out know

This approach is theoretically feasible, but not yet found to achieve better data structure, if you have suggestions, please advise generous.

Title two Source

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int room_number=0;
int destination=0;
struct room
{
    int a;
    int b;
    bool operator<(const room& ano)
    {
         return a<ano.a;
    }
}a[25001];
int choose(int begin,int end)
{
    int cnt=0;
    int j=0;
    int flag=0;
    for(int i=0;i<room_number;i++)
    {
        int max_choose=-2e9;
        for(j=i;j<room_number && a[j].a<=begin;j++)
        {
            max_choose=max(max_choose,a[j].b);
        }
        if(max_choose<begin)
        {
            cnt=-1;
            break;
        }
        cnt++;
        if(max_choose>=end)
        {
        	flag=1;
            break;
        }
        i=j-1;
        begin=max_choose+1;
    }
    if(flag==1)
    return cnt;
    else
    return -1;
}
int main()
{
    while(scanf("%d%d",&room_number,&destination)!=EOF)
    {
    	for(int i=0;i<room_number;i++)
    	{
    		a[i].a=0;
    		a[i].b=0;
		}
        int begin,end=0;
        for(int i=0;i<room_number;i++)
        {
            scanf("%d %d",&begin,&end);
                a[i].a=begin;
                a[i].b=end;
        }
        sort(a,a+room_number);
        int number=choose(1,destination);
        cout<<number<<endl;
    }
    return 0;
}
Published 17 original articles · won praise 2 · Views 1662

Guess you like

Origin blog.csdn.net/qq_43942251/article/details/104807616