给出一个长度为N的无序数组,数组中的元素为整数,有正有负包括0,并互不相等。从中找出所有和 = 0的3个数的组合。如果没有这样的组合,输出No Solution。如果有多个,按照3个数中最小的数从小到大排序,如果最小的数相等则按照第二小的数排序。
Input
第1行,1个数N,N为数组的长度(0 <= N <= 1000)
第2 - N + 1行:A[i](-10^9 <= A[i] <= 10^9)
Output
如果没有符合条件的组合,输出No Solution。
如果有多个,按照3个数中最小的数从小到大排序,如果最小的数相等则继续按照第二小的数排序。每行3个数,中间用空格分隔,并且这3个数按照从小到大的顺序排列。
Input示例
7
-3
-2
-1
0
1
2
3
Output示例
-3 0 3
-3 1 2
-2 -1 3
-2 0 2
-1 0 1
搞得好忧伤啊,,,一直用long在做,,结果。。。被自己坑了,,,
#include "iostream"
#include <algorithm>
#include <set>
using namespace std;
#define N 1005
#define M 499500
struct group
{
long long fi;
long long sc;
long long th;
};
void mysort(group &gr)
{
if (gr.th < gr.fi)
{
long long temp = gr.th;
gr.th = gr.sc;
gr.sc = gr.fi;
gr.fi = temp;
}
else if (gr.th > gr.fi && gr.th < gr.sc)
{
long long temp = gr.sc;
gr.sc = gr.th;
gr.th = temp;
}
}
struct func_Sort
{
bool operator()(const group &yy, const group &xx)
{
if (yy.fi < xx.fi) return true;
else if (yy.fi == xx.fi && yy.sc < xx.sc) return true;
else if (yy.fi == xx.fi && yy.sc == xx.sc && yy.th < xx.th) return true;
return false;//这里仿函数对set容器中的内容进行排序
}
};
group gro[M];
int main()
{
set<group, func_Sort> grou;
int L[N];
bool flag = false;
int num;
cin >> num;
for (int i = 0; i < num; i++)
{
cin >> L[i];
}
sort(L, L + num);
int m = 0;
for (int i = 0; i < num; i++)
{
for (int j = i + 1; j < num; j++)
{
gro[m].fi = L[i];
gro[m++].sc = L[j];
}
}
m--;
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < num; ++j)
{
if (gro[i].fi != L[j] && gro[i].sc != L[j] && (gro[i].fi + gro[i].sc + L[j] == 0))
{
gro[i].th = L[j];
mysort(gro[i]);//每一组中的数字进行排序,然后insert到set容器中
grou.insert(gro[i]);
flag = true;
break;
}
}
}
if (flag)
{
for (set<group>::iterator it = grou.begin(); it != grou.end(); it++)
{
cout << it->fi << " " << it->sc << " " << it->th << endl;
}
}
else
cout << "No Solution" << endl;
return 0;
}
51nod1090 3个数和为0
最新推荐文章于 2022-07-19 15:53:16 发布