题意:给一个集合,求d=a+b+c,d最大且a,b,c,d下标不能是同一个
解题思路
a+b=d-c
另外,可以OJ看下0ms大佬们的代码.
#include "pch.h"
#include <string>
#include<iostream>
#include<map>
#include<memory.h>
#include<vector> namespace cc
{
using std::cout;
using std::endl;
using std::cin;
using std::map;
using std::vector;
class Add
{ public:
int ai;
int bi;
int sum;
Add() {};
Add(int a, int b, int sum) :ai(a), bi(b) {
this->sum = sum;
}
}; constexpr int N = 1000;
int a[N];
int n; map<int, vector<Add>> addMaps;
int ok;
int d; int cmp(void const* v1, void const* v2)
{
int* k1 = (int*)v1;
int* k2 = (int*)v2;
return *k1 - *k2;
} void dump()
{
for (int i = 0;i < n;i++)
{
cout << " " << a[i];
}
cout << endl;
} void add()
{
using IT = map<int, vector<Add>>::iterator;
for (int i = 0;i < n - 1;i++)
for (int j = i + 1;j < n;j++)
{
//all a+b
auto sum = a[i] + a[j];
Add A(i, j, sum);
IT it = addMaps.find(sum);
if (it == addMaps.end())
{
vector<Add> v;
v.push_back(A);
addMaps[sum] = v;
}
else
{
it->second.push_back(A);
}
} //all d-c
for (int i = n - 1;i >= 0 && ok == 0;i--)
{
for (int j = n - 1;j >= 0;j--)
{
if (i == j)
continue;
auto sub = a[i] - a[j];
IT it = addMaps.find(sub);
if (it == addMaps.end())
{
continue;
}
vector<Add> adds = addMaps[sub];
for (int k = 0;k < adds.size();k++)
{
if (adds[k].ai != i && adds[k].ai != j && adds[k].bi != i && adds[k].bi != j)
{
ok = 1;
d = a[i];
}
}
if (ok)
break;
}
} } void read()
{
memset(a, 0, sizeof(a));
ok = 0;
addMaps.clear();
for (int i = 0;i < n;i++)
{
cin >> a[i];
}
//sort,cong xiao dao da
qsort(a, n, sizeof(int), cmp);
//dump();
} void solve()
{
while (cin >> n && n)
{
read();
add();
if (ok)
cout << d << endl;
else
cout << "no solution" << endl;
} } }; int main()
{ #ifndef ONLINE_JUDGE
freopen("d://1.text", "r", stdin);
#endif // !ONLINE_JUDGE
cc::solve(); return 0;
}