Chieh's Blog

Because Of Coding

ZOJ Problem Set - 2029 The Intervals

Chieh posted @ 2015年7月29日 14:18 in ZOJ , 268 阅读

飞机票:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2029

题意:就是给你n个数,和m个查询,每个查询有个数q.从n个数选两个数,假设为a,b(a<b),使得q在区间[a,b)内。并且要求这个b-a最小。

分析:起先要是b-a最小又要包含t。我们可以将n个数排序,然后取两个数a,b,使得,a<=t<b,并且a和b越接近越好,为什么呢?因为越接近的话b-a就越小,因为我们排了序。然后具体a和b我们可以二分查找位置,然后特殊情况稍微处理一下就可以了,最后啪啪啪就可以AC了

/*
Author:Chieh
Because Of Coding
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include <stack>
#define LL long long
#define INF 1e9
#define EPS 1e-9
using namespace std;
vector<int> V;
int n,m;
void init()
{
    V.clear();
    int u;
    for(int i=1; i<=n; i++)
    {
        scanf("%d",&u);
        V.push_back(u);
    }
    sort(V.begin(),V.end());
}

void play()
{
    int t;
    while(m--)
    {
        scanf("%d",&t);
        int pos1=lower_bound(V.begin(),V.end(),t)-V.begin();
        int pos2=upper_bound(V.begin(),V.end(),t)-V.begin();
        if(pos1==n||pos2==n)
        {
            printf("no such interval\n");
            continue;
        }
        if(pos1!=pos2)
        {
            printf("[%d,%d)\n",V[pos1],V[pos2]);
            continue;
        }
        if(pos1==0)
        {
            printf("no such interval\n");
            continue;
        }
        printf("[%d,%d)\n",V[pos1-1],V[pos1]);

    }
    printf("\n");
}
int main()
{
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        init();
        play();
    }
    // cout << "Hello world!" << endl;
    return 0;
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter