#UVa:11057-Exact Sum

灆洢 2016-03-15 01:48:17

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

C++(0.209)

/*******************************************************/
/* UVa 11057 Exact Sum                                 */
/* Author: Maplewing [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;
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

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