1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
#include <iostream> #include <cstdlib> #include <cstdio> #define SZ 10005 #define INF 100000000 #define ll long long using namespace std; ll a[SZ]; int main() { ll N,M,MN; bool f=0; ll price2,price1; price2 = 1000001; price1 = 1000001; int d = price1+price2; //cout<<d<<"\n"; while(cin>>N) { MN = INF; for(int i=0;i<N;i++) cin>>a[i]; cin>>M; for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { if(a[i]+a[j]==M && i!=j) { if(abs(a[i]-a[j])<MN) { MN = abs(a[i]-a[j]); price1 = a[i]; price2 = a[j]; } } } }//for loop if(price1>price2) { price1 = price1 + price2; price2 = price1 - price2; price1 = price1 - price2; } cout<<"Peter should buy books whose prices are "<<price1<<" and "<<price2<<".\n\n"; }//while } |
Another way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #define INF 10000000 using namespace std; bool val[1000005]; int arr[10005]; int main() { int N,tmp,d; int total,diff; int I,J; while(scanf("%d",&N)!=EOF) { memset(arr,0,sizeof(arr)); memset(val,0,sizeof(val)); diff=INF; for(int i=0;i<N;i++) { cin>>arr[i]; val[arr[i]]=1; } cin>>total; for(int i=0;i<N;i++) { tmp=total-arr[i]; if(tmp<0) continue; if(tmp>1000001) continue; if(val[tmp]) { d = abs(arr[i]-tmp); if(d<diff) { diff=d; I=arr[i]; J=tmp; } } } if(I>J) { I=I+J; J=I-J; I=I-J; } cout<<"Peter should buy books whose prices are "<<I<<" and "<<J<<".\n\n"; } return 0; } |