資料結構與演算法——在一定範圍內求最少標記點

readyao發表於2015-12-14



思路就是每到一個點的時候,不要首先想著把它標記,而是應該先看前面的那個點是否已經標記:
如果前面的那個點沒有標記,並且該點後面的點到前面的那個點的距離大於R,則將當前點標記;
如果前面的那個點沒有標記,並且該點後面的點到前面的那個點的距離小於R,則不標記當前點;

每次都不想標記當前點,總是想著標記後面的那個點也可以;當實在是不行的時候再標記當前點;

虛擬碼:
if(i = 1)
if(X(i+1)- X(i) > R) 
將Xi標記book[i] == 1
else 
i++
else if(i<N)
if(book[i-1] == 0  &&  X(i+1)- X(i-1)>R )
將Xi標記book[i] == 1
else if(book[i-1] == 0  &&  X(i+1)- X(i-1)<R)
i++;
else if (i == N && X(i)- X(i-1)> R)
將Xi標記book[i] == 1


/*************************************************************************
	> File Name: 224.cpp
	> Author: 
	> Mail: 
	> Created Time: 2015年12月14日 星期一 21時38分27秒
 ************************************************************************/

#include <iostream>
#include <vector>
using namespace std;

void input_data(int * number, int * r, vector<int>  & x, vector<int> &book)
{
    cout << "輸入點的個數:";
    cin >> *number;
    cout << "輸入半徑的大小: ";
    cin >> *r;
    cout << "輸入每個點的位置: ";
    int i = 0;
    int val;

    while(i != *number){
        cin >> val;
        x.push_back(val);
        book.push_back(0);
        cin.get();
        i++;
    }
}


void output_data(int * number, int *r, vector<int> & x, vector<int> &book)
{
    cout << "N = " << *number << endl;
    cout << "r = " << *r << endl;
    cout << "X = ";
    for (vector<int>::iterator pos = x.begin(); pos != x.end(); ++pos){
        cout << *pos << " ";
    }
    cout << endl;
    for (vector<int>::iterator pos = book.begin(); pos != book.end(); ++pos){
        cout << *pos << " ";
    }
    cout << endl;
}

void solve(int * number, int * r, vector<int> & x, vector<int> & book)
{
    int i = 0;
    while(i < x.size()){
        if(i == 0){
            if(x[i+1] - x[i] > *r){
                book[i] = 1;
            }
        }
        else if(i < *number-1){
            if(book[i-1] == 0 && x[i+1]-x[i-1] > *r){
                book[i] = 1;
            }
        }
        else if (i == *number-1 && x[i]-x[i-1] > *r){
            book[i] = 1;
        }
        i++;
    }

    cout << "the result is :";
    for (i = 0; i < book.size(); ++i){
        if (book[i] == 1)
            cout << x[i] << " ";
    }
    cout << endl;
}


int main()
{
    int N, R;
    vector<int> X;
    vector<int> book;

    input_data(&N, &R, X, book);
    //output_data(&N, &R, X, book);
    solve(&N, &R, X, book);

    return 0;
}


相關文章