I have to build a program as bellow:
I done the program as bellow:
#include<iostream>
using namespace std;
int main() {
int a,b,c,n,i,j;
cin >> a;
cin >> b;
cin >> c;
cin >> n;
int num[n];
for(i=0;i<n;i++) {
cin >> num[i];
}
for (i=0;i<n;i++)
for (j=i+1;j<n;j++) {
if(a*num[i]*num[i]+b*num[j]*num[j] == c) {
cout << "(" << num[i] << "," << num[j] << ")";
}
if(a*num[j]*num[j]+b*num[i]*num[i] == c) {
cout << "(" << num[j] << "," << num[i] << ")";
}
}
return 0;
}
I made it by O(nlogn) with two 'for' statements but i know it could be done by O(n).
NOTE THAT MY PROGRAM WORKS AND I DON'T NEED TO ADD EXPECTED OUTPUT AND MY CURRENT OUTPUT AS YOU SAID IN THE COMMENTS. I ONLY WANT IT TO BE O(N) not O(nlogn) -> I WANT AN OPTIMIZED VERSION OF THE CODE!
How can I do this?
Example of running program: a=1, b=1, c=20 Then n = 5 Then n numbers: 2 3 4 9 18 Program will show all pairs (x,y) which verifies the equation x^2 + y^2 = 20. In this case it shows (2,4) and (4,2).
Thank you!
答案 0 :(得分:1)
Assuming 0 based index...
Set i=0
Set j=n-1
While i<n or j>=0
Set sum=a(num[i]^2)+b(num[j^2)
If sum==c then found pair, and increase i
If sum<c increase i
If sum>c decrease j
答案 1 :(得分:0)
我发现这个问题在这里解决了:http://lonews.ro/educatie-cultura/22899-rezolvare-admitere-universitatea-bucuresti-2015-pregatire-informatica.html并稍微改了一下以显示对(它最初显示了对的数量)。
#include <iostream>
using namespace std;
int main()
{
int a, b, c, n, i=0;
cout << "a = ";
cin >> a;
cout << "b = ";
cin >> b;
cout << "c = ";
cin >> c;
cout << "n = ";
cin >> n;
int s[n];
for(i=0; i<n; i++) {
cout << "s[" << i+1 << "] = ";
cin >> s[i];
}
int j=n-1;
i = 0;
while(j>=0 || i<n) {
if(a*s[i]*s[i] + b*s[j]*s[j] == c) {
cout << "(" << s[i] << "," << s[j] << ") ";
i++;
}
if(a*s[i]*s[i] + b*s[j]*s[j] < c) {
i++;
}
if(a*s[i]*s[i] + b*s[j]*s[j] > c) {
j--;
}
}
return 0;
}