python3做法:
n = int(input())
lst= list(map(int,input().split()))
times = []
for i in lst:
for j in lst:
if i < j and i + j in lst and i+j not in times:
times.append(i+j)
print(len(times))
c语言做法
#include<stdio.h>
int main()
{
int n, i, j, k, count = 0, temp;
scanf("%d", &n);
int a[101] = {0};
int b[101] = {0};
for (i = 0; i < n; i++) //输入
{
scanf("%d", &a[i]);
b[i] = a[i];
}
for (i = 0; i < n - 1; i++) //排序
{
for (j = 0; j < n - 1 - i; j++)
{
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
temp = a[i] + a[j];
for (k = 0; k < n; k++)
{
if (temp == b[k])
{
count++;
b[k] = 0;
continue;
}
}
}
}
printf("%d\n", count);
return 0;
}
c++做法:
#include<iostream>
#include<algorithm>
#include"vector"
using namespace std;
/* int exist(int temp, vector<int> &vec) //判断temp是否在vec 中存在 { auto it = find(vec.begin(), vec.end(), temp); if (it != vec.end()) //查找成功 { vec.erase(it); return 1; } else return 0; } */
int exist(int temp, vector<int>& vec)
{
for(vector<int>::iterator it = vec.begin(); it != vec.end(); it++)
{
if (temp == *it)
{
*it = 0; //把已经确定的数等于0,防止重复
return 1;
}
}
return 0;
}
int main()
{
vector<int> vec1, vec2;
int n = 0, count = 0;
cin >> n;
while (n--)
{
int t = 0;
cin >> t;
vec1.push_back(t);
}
sort(vec1.begin(), vec1.end()); //在algorithm中
vec2 = vec1;
for (auto it = vec1.begin(); it != vec1.end(); it++)
{
for (auto it2 = it + 1; it2 != vec1.end(); it2++)
{
auto temp = *it + *it2;
if (exist(temp, vec2))
{
count++;
}
}
}
cout << count << endl;
return 0;
}