hihocoder练习赛54

最小差值


#1722 : 最小差值

时间限制: 10000ms
单点时限: 1000ms
内存限制: 256MB

描述

给定N个数组,每个数组都包含M个整数。  

现在你被要求从每个数组中选出一个数,总共N个数,然后求出其中最大与最小的差值。  

在MN种选法中,差值最小是多少?

输入

第一行包含两个整数N和M。  

以下N行,每行包含M个整数。  

对于50%的数据,1 ≤ N × M ≤ 10000  

对于100%的数据,1 ≤ N × M ≤ 200000 0 ≤ 每个整数 ≤ 1000000

输出

最小的差值

样例输入
3 3  
8 1 6      
3 5 7  
4 9 2
样例输出
2

思路:将所有序列排在一个排序数组内,当然要保存原来那个数的组别,然后在数组内进行尺取,每次尺取的状态是要有n个组,每次尺取的值是最小值前去最小值。

code:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5 + 10;
#define INF 0x3f3f3f3f
#define clr(x,y) memset(x,y,sizeof x)


struct Node
{
    bool operator < (Node t)
    {
        return x < t.x;
    }
    int x,id;
}a[maxn];

map<int,int>ms;
int main()
{
    int n,m;
    while(cin >> n >> m)
    {
        int len = 0;
        for(int i = 1;i <= n;i ++)
        {
            for(int j = 1;j <= m;j ++)
            {
                int x;cin >> x;
                a[++ len] = (Node){x,i};
            }
        }
        sort(a + 1,a + len + 1);

        ms.clear();
        int l = 1,r = 0;

        int ans = INF;
        while(l <= len)
        {
            while(r < len && ms.size() < n)
            {
                ms[a[++r].id] ++;
            }
            if(ms.size() == n)
            {
                ans = min(ans,a[r].x - a[l].x);
            }
            else break;
            ms[a[l].id] --;
            if(ms[a[l].id] == 0)ms.erase(a[l].id);
            l ++;
        }
        cout << ans << endl;
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/xiaolonggezte/article/details/79865374
今日推荐