Problem Statement
????
You are given a set A of integers and a positive integer n. You must find positive integers x, y and z such that their product is as close to n as possible (minimize |n - x * y * z|), and none of them belongs to A. If there are several such triples, find the one with the smallest x. If there are still several such triples, minimize y. If there is still a tie, minimize z.
You are given the elements of A as a vector <int> a. Return a vector <int> with exactly three elements: x, y and z, in this order.
Definition
????
Class:
AvoidingProduct
Method:
getTriple
Parameters:
vector <int>, int
Returns:
vector <int>
Method signature:
vector <int> getTriple(vector <int> a, int n)
(be sure your method is public)
????
Constraints
-
a will contain between 0 and 50 elements, inclusive.
-
Each element of a will be between 1 and 1000, inclusive.
-
All elements of a will be distinct.
-
n will be between 1 and 1000, inclusive.
Examples
0)
????
{2,4}
4
Returns: {1, 1, 3 }
You can get 3=1*1*3 and 5=1*1*5. 3 is better.
1)
????
{1}
10
Returns: {2, 2, 2 }
2)
????
{1,2}
10
Returns: {3, 3, 3 }
3)
????
{1,3}
12
Returns: {2, 2, 2 }
4)
????
{1,3}
13
Returns: {2, 2, 4 }
5)
????
{1,15}
90
Returns: {2, 5, 9 }
第一次做1000分题目,花了三个小时,大汗淋漓......
This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.
#include<iostream>
#include<vector>
#include<cmath>
#include<algorithm>
#include <iterator>
using namespace std;
class AvoidingProduct
{
public:
bool noFound(vector <int>b,int m)
{
bool flag=true;
for(int i=0;i<b.size();i++)
{
if (b.at(i)==m)
{
flag =false;
break;
}
}
return flag;
}
vector <int> getTriple(vector <int> a, int n)
{
long min=1000000000;
vector <int> re;
for(int x=1;x<n;x++)
{
if(noFound(a,x))
{
for(int y=1;y<n;y++)
{
if (noFound(a,y))
{
for(int z=1;z<n;z++)
{
if (noFound(a,z))
{
int temp=abs(x*y*z-n);
if(temp<min)
{
min=temp;
re.clear();
re.push_back(x);
re.push_back(y);
re.push_back(z);
}
if(temp==min)
{
if (re.size()==0)
{
re.clear();
re.push_back(x);
re.push_back(y);
re.push_back(z);
}
else
{
int count1=100*re.at(0)+10*re.at(1)+re.at(2);
int count2=100*x+10*y+z;
if (count1>count2)
{
re.clear();
re.push_back(x);
re.push_back(y);
re.push_back(z);
}
};
}
// if(temp>min) break;
}
}
}
}
}
}
return re;
}
};