第一道:相反数
问题描述
有 N 个非零且各不相同的整数。请你编一个程序求出它们中有多少对相反数(a 和 -a 为一对相反数)。
输入格式
第一行包含一个正整数 N。(1 ≤ N ≤ 500)。
第二行为 N 个用单个空格隔开的非零整数,每个数的绝对值不超过1000,保证这些整数各不相同。
输出格式
只输出一个整数,即这 N 个数中包含多少对相反数。
样例输入
5
1 2 3 -1 -2
样例输出
2
做法
#include <iostream>
using namespace std;
int main() {
int N,count=0;
int a[2000];
cin >> N;
for (int i; i < N;i++) {
cin >> a[i];
}
for (int i = 0;i < N;i++) {
for (int j = 0;j < N;j++) {
if (a[j] == -a[i]) {
count++;
}
}
}
count = count / 2;
cout << count << endl;
return 0;
}
第二道
问题描述
有 N 个非零且各不相同的整数。请你编一个程序求出它们中有多少对相反数(a 和 -a 为一对相反数)。
输入格式
第一行包含一个正整数 N。(1 ≤ N ≤ 500)。
第二行为 N 个用单个空格隔开的非零整数,每个数的绝对值不超过1000,保证这些整数各不相同。
输出格式
只输出一个整数,即这 N 个数中包含多少对相反数。
样例输入
5
1 2 3 -1 -2
样例输出
2
做法
1、使用结构体存储窗口的两对坐标
2、循环输入点击位置的坐标,并判断它位于第几个窗口
3、选中窗口后将此窗口结构体的层数设置为最大,每次判断之后使用sort重新排序
#include <iostream>
#include<algorithm>
using namespace std;
struct point {
int x1, x2, y1, y2;
int layer;
int number;
};//当有超过一个的变量时考虑结构体,之前用的二维数组难用死了
bool cmp(point x, point y) {//编写排序规则
return x.layer > y.layer;
}
int main() {
struct point p[15];//结构体在main函数里要重新声明一下
int N, M,i,j;
int x, y;
cin >> N >> M;
for (i = 0;i < N;i++) {
cin >> p[i].x1 >> p[i].y1 >> p[i].x2 >> p[i].y2;
p[i].layer = i+1;
p[i].number = i+1;
}
bool flag = 0;//当点击在任何窗口之外时显示未选中
int max = N + 1;
for (i = 0;i < M;i++) {
cin >> x >> y;
sort(p, p + N, cmp);//把p从大到小排个序,保证最后选中的在最上面
for (j = 0;j < N;j++) {
if (x >= p[j].x1 &&x<= p[j].x2 && y >= p[j].y1 && y<= p[j].y2) {
cout << p[j].number << endl;
p[j].layer = max;
flag = 1;
break;
}
}
if (flag == 0) {
cout << "IGNORED" << endl;
}
flag = 0;
max++;
}
return 0;
}