股票买卖 II
题目大意
给定一个长度为 N N N 的数组,数组中的第 i i i 个数字表示一个给定股票在第 i i i 天的价格。设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
输入格式
第一行包含整数 N N N,表示数组长度。
第二行包含 N N N 个不大于 10000 的正整数,表示完整的数组。
输出格式
输出一个整数,表示最大利润。
数据范围:1≤N≤105
输入样例
6
7 1 5 3 6 4
输出样例
7
样例解释:样例1:在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。共得利润 4+3 = 7。
#include <cstdio>
using namespace std;
const int maxn = 1e5 + 7;
int a[maxn];
int main()
{
int n;
scanf("%d",&n);
for(int i = 0; i < n; i++) scanf("%d",&a[i]);
int res = 0;
for(int i = 1; i < n; i++)
if(a[i]-a[i-1] > 0) res += a[i] - a[i-1];
printf("%d\n",res);
return 0;
}
货仓选址
题目大意
在一条数轴上有 N N N 家商店,它们的坐标分别为 A 1 A_1 A1~ A N A_N AN。
现在需要在数轴上建立一家货仓,每天清晨,从货仓到每家商店都要运送一车商品。
为了提高效率,求把货仓建在何处,可以使得货仓到每家商店的距离之和最小。
输入格式
第一行输入整数 N N N。
第二行N个整数 A 1 A N A_1~A_N A1 AN。
输出格式
输出一个整数,表示距离之和的最小值。
数据范围:1≤ N N N≤100000
输入样例
4
6 2 9 1
输出样例
12
将 n n n 个点从小到大排序,找到中点,最后求绝对值之和,要防止爆 i n t int int
#include <cstdio>
#include <algorithm>
using namespace std;
int a[100007];
int main()
{
int n;
scanf("%d",&n);
for(int i = 1; i <= n; i++) scanf("%d",&a[i]);
sort(a+1, a + 1 + n);
int mid = a[n+1>>1];
long long ans = 0;
for(int i = 1; i <= n; i++)
ans += abs(mid - a[i]);
printf("%d\n",ans);
return 0;
}
糖果传递
题目大意
有 n n n 个小朋友坐成一圈,每人有 a [ i ] a[i] a[i] 个糖果。每人只能给左右两人传递糖果。每人每次传递一个糖果代价为1。求使所有人获得均等糖果的最小代价。
输入格式
第一行输入一个正整数 n n n,表示小朋友的个数。
接下来 n n n 行,每行一个整数 a [ i ] a[i] a[i],表示第i个小朋友初始得到的糖果的颗数。
输出格式
输出一个整数,表示最小代价。
数据范围: 1 ≤ n ≤ 1000000 1≤n≤1000000 1≤n≤1000000 数据保证一定有解。
输入样例
4
1
2
5
4
输出样例
4
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 7;
int a[maxn],c[maxn];
int main()
{
int n; ll sum = 0;
scanf("%d",&n);
for(int i = 1; i <= n; i++) scanf("%d",&a[i]),sum += a[i];
ll ave = sum / n;
for(int i = 2; i <= n; i++) c[i] = c[i-1] + ave - a[i];
sort(c+1,c+1+n);
ll ans = 0;
for(int i = 1; i <= n; i++) ans += abs(c[i] - c[n+1>>1]);
printf("%lld\n",ans);
return 0;
}
雷达设备
题目大意
假设海岸是一条无限长的直线,陆地位于海岸的一侧,海洋位于另外一侧。每个小岛都位于海洋一侧的某个点上。
雷达装置均位于海岸线上,且雷达的监测范围为 d d d,当小岛与某雷达的距离不超过 d d d 时,该小岛可以被雷达覆盖。
我们使用笛卡尔坐标系,定义海岸线为x轴,海的一侧在x轴上方,陆地一侧在 x x x 轴下方。
现在给出每个小岛的具体坐标以及雷达的检测范围,请你求出能够使所有小岛都被雷达覆盖所需的最小雷达数目。
输入格式
第一行输入两个整数 n n n 和 d d d,分别代表小岛数目和雷达检测范围。
接下来 n n n 行,每行输入两个整数,分别代表小岛的 x , y x,y x,y 轴坐标。
同一行数据之间用空格隔开。
输出格式
输出一个整数,代表所需的最小雷达数目,若没有解决方案则所需数目输出“-1”。
数据范围: 1 ≤ n ≤ 1000 1≤n≤1000 1≤n≤1000
输入样例
3 2
1 2
-3 1
2 1
输出样例
2
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1e3 + 7;
struct node{
double l, r; //左端点,右端点
bool operator < (const node &t) const{
return r < t.r; //右端点从小到大排序
}
};
node a[maxn];
int vis[maxn]; // 1 表示当前区间存在, 0 表示被覆盖
double x[maxn], y[maxn]; //坐标x,y
int main()
{
int n, d, ok = 0;
scanf("%d%d",&n,&d);
for</