https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=24&problem=1998&mosmsg=Submission+received+with+ID+17773698
題目大意:給你一個數列a,長度n(1<=n<=10^4)跟一個數字s。求出ai, aj(i!=j),符合ai+aj=s 且 |ai-aj| 最小。
用一個set維護所有元素即可XD。
#include <iostream>
#include <stdio.h>
#include <set>
using namespace std;
const int MAX_N = 1e4 + 5;
int a[MAX_N];
int main () {
int n;
while (scanf("%d",&n) != EOF) {
set<int> s;
for (int x=0;n>x;x++) {
scanf("%d",&a[x]);
s.insert(a[x]);
}
int i;
scanf("%d",&i);
int times=0;
int ans=0;
for (int x=0;n>x;x++) {
if (a[x]*2==i) times++;
else if (s.find(i-a[x]) != s.end()) {
ans = max(ans,min(a[x],i-a[x]));
}
}
if (times>=2) printf("Peter should buy books whose prices are %d and %d.\n",i/2,i/2);
else printf("Peter should buy books whose prices are %d and %d.\n",ans,i-ans);
puts("");
}
}
沒有留言:
張貼留言