NBUT1477:AmeriDarts

http://ac.nbutoj.com/Problem/view.xhtml?id=1477

  • 问题描述
  • AmeriDarts is a dangerous but full of glamour. Mr.cai wants to have a try.
    The rule is simple:throw some boomerangs in a line from left to right as quickly as you can. You are asked to throw twice, first time throw A red boomerangs, second time throw B blue boomerangs. Your score is to calculate the shortest length of blue and red boomerang. This rule seems strange? so am I.
  • 输入
  • First there is two integer A(no more than 1000) and B(no more than 1000), then followed two lines consist of those A and B numbers.Note that these two array both in ascending order.
  • 输出
  • For each testcase, output the shortest length between red and blue boomerang in a single line.
  • 样例输入
  • 4 4
    1 2 3 4
    5 6 7 8
    5 5
    5 12 14 15 16
    1 2 7 8 9
    
  • 样例输出
  • 12

     

    题意:找出两个数组中数字差距最小的距离

    思路:由于数组是递增的,所以只要记录b数组比较到了那个数即可,无需回溯

     

    #include <stdio.h>
    #include <algorithm>
    using namespace std;
    
    int jian(int a,int b)
    {
        int k = a-b;
        if(k<0)
        return -k;
        return k;
    }
    
    int main()
    {
        int n,m,i,j,l,t;
        int a[1005],b[1005],c[1005];
        while(~scanf("%d%d",&n,&m))
        {
            l = 0;
            for(i = 1;i<=n;i++)
            scanf("%d",&a[i]);
            for(i = 1;i<=m;i++)
            scanf("%d",&b[i]);
            b[0] = 0;
            b[m+1] = 0;
            t = 1;
            for(i = 1;i<=n;i++)
            {
                for(j = t;j<=m;j++)
                {
                    if(jian(a[i],b[j])<jian(a[i],b[j-1]) && jian(a[i],b[j])<jian(a[i],b[j+1]))//找到差距最小的地方
                    {
                        t = j;//记录b数组所到的位置,放置回溯,节约时间
                        c[l++] = jian(a[i],b[j]);
                    }
                }
            }
            sort(c,c+l);
            printf("%d\n",c[0]);
        }
    
        return 0;
    }
    


     

  • 你可能感兴趣的:(波大)