51Nod 1001数组中和等于K的数对
Input示例
8 9 -1 6 5 3 4 2 9 0 8
Output示例
-1 9 0 8 2 6 3 5
first try:
#include "bits/stdc++.h" using namespace std; #define LL long long #define INF 0x3f3f3f3f3f #define PI acos(-1) #define N 50010 int arr[N]; int main() { int n,k; while(~scanf("%d%d",&k,&n)){ for(int i=0;i<n;i++){ scanf("%d",&arr[i]); } sort(arr,arr+n); int c=0; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(arr[i]+arr[j]==k){ printf("%d %d\n",arr[i],arr[j]); c++; } } } if(!c){ printf("No Solution\n"); } } return 0; }
O(n^2)
Time limit exceeded,优化
second try:
第二层从后向前找,及时跳出
#include "bits/stdc++.h" using namespace std; #define LL long long #define INF 0x3f3f3f3f3f #define PI acos(-1) #define N 50010 int arr[N]; int main() { int n,k; while(~scanf("%d%d",&k,&n)){ for(int i=0;i<n;i++){ scanf("%d",&arr[i]); } sort(arr,arr+n); int c=0; for(int i=0;i<n;i++){ for(int j=n-1;j>=i+1;j--){ if(arr[i]+arr[j]==k){ printf("%d %d\n",arr[i],arr[j]); c++; break; } } } if(!c){ printf("No Solution\n"); } } return 0; }
Time limit exceeded,再优化
third try:
转换思维,查找互补数是否存在,二分查找,分治
#include "bits/stdc++.h" using namespace std; #define LL long long #define INF 0x3f3f3f3f3f #define PI acos(-1) #define N 50010 int arr[N]; int Find(int n,int x){ int r=n-1,l=0,m; while(l<=r){ m=(r+l)/2; if(x==arr[m]) return m; else if(x>arr[m]) l=m+1; else r=m-1; } return -1; } int main() { int n,k; while(~scanf("%d%d",&k,&n)){ for(int i=0;i<n;i++){ scanf("%d",&arr[i]); } sort(arr,arr+n); int c=0,tt; for(int i=0;i<n;i++){ tt=Find(n,k-arr[i]); if(tt!=-1){ if(tt<=i) break; printf("%d %d\n",arr[i],k-arr[i]); c++; } } if(!c){ printf("No Solution\n"); } } return 0; }