#UVa:11057-Exact Sum

兩兩尋找,找出兩者總和剛好為所要求之值並且兩者差距最小的數對即是答案。

C++(0.209)

/*******************************************************/
/* UVa 11057 Exact Sum                                 */
/* Author: LanyiKnight [at] knightzone.studio             */
/* Version: 2016/03/15                                 */
/*******************************************************/
#include <iostream>
#include <cstdio>
#include <climits>
#include <algorithm>
using namespace std;

int main(){
  int N;
  while( scanf("%d", &N) != EOF ){
    int books[10005] = {0};
    for( int i = 0 ; i < N ; ++i ){
      scanf("%d", &books[i]);
    }

    int sum;
    scanf("%d", &sum);

    sort(books, books+N);

    int exactI, exactJ, diff = INT_MAX;
    for( int i = 0 ; i < N ; ++i ){
      for( int j = i+1 ; j < N ; ++j ){
        if( books[i] + books[j] == sum && books[j] - books[i] < diff ){
          exactI = books[i];
          exactJ = books[j];
        }
      }
    }

    printf("Peter should buy books whose prices are %d and %d.\n\n", exactI, exactJ);
  }
  return 0;
}
廣告

Comment

There is no comment on this post. Be the first one.

發表迴響

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料

%d 位部落客按了讚: