NOIP普及组 龙虎斗 题解
NOIP 普及组
+++
龙虎斗
轩轩和凯凯正在玩一款叫《龙虎斗》的游戏,游戏的棋盘是一条线段,线段上有 𝑛 个兵营(自左至右编号 1 ~ 𝑛),相邻编号的兵营之间相隔 1 厘米,即棋盘为长度为 𝑛−1 厘米的线段,𝑖 号兵营里有 ci 位工兵。
下面图为 𝑛=6 的示例:
轩轩在左侧,代表“龙”;凯凯在右侧,代表“虎”。
他们以 m 号兵营作为分界,靠左的工兵属于龙势力,靠右的工兵属于虎势力,而第 𝐦 号兵营中的工兵很纠结,他们不属于任何一方。
一个兵营的气势为:该兵营中的工兵数 × 该兵营到 m 号兵营的距离;参与游戏一方的势力定义为:属于这一方所有兵营的气势之和。
下面图为 n=6,𝑚=4 的示例,其中红色为龙方,黄色为虎方:
游戏过程中,某一刻天降神兵,共有 s1 位工兵突然出现在了 p1 号兵营。
作为轩轩和凯凯的朋友,你知道如果龙虎双方气势差距太悬殊,轩轩和凯凯就不愿意继续玩下去了。
为了让游戏继续,你需要选择一个兵营 p2,并将你手里的 s2 位工兵全部派往兵营 p2,使得双方气势差距尽可能小。
注意:你手中的工兵落在哪个兵营,就和该兵营中其他工兵有相同的势力归属(如果落在 m 号兵营,则不属于任何势力)。
输入格式
输入文件的第一行包含一个正整数 𝑛,代表兵营的数量。
接下来的一行包含 𝑛 个正整数,相邻两数之间以一个空格分隔,第 𝑖 个正整数代表编号为 𝑖 的兵营中起始时的工兵数量 ci。
接下来的一行包含四个正整数,相邻两数间以一个空格分隔,分别代表 m,p1,s1,s2。
输出格式
输出文件有一行,包含一个正整数,即 p2,表示你选择的兵营编号。
如果存在多个编号同时满足最优,取最小的编号。
数据范围
1<m<n,
1≤p1≤n,
n≤1e5,ci,s1,s2≤1e9
输入样例:
6
2 3 2 3 2 3
4 6 5 2
输出样例:
2
分析:
纯碎的模拟,记得开long long 记得开long long
被long long搞心态了,不想优化代码了,下次一定。
AC CODE 1
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstdio>
using namespace std;
typedef long long LL;
const int N = 100010;
LL a[N];
LL n, m, p1, s1, s2;
int main()
{
scanf("%lld", &n);
for (int i = 1; i <= n; i ++ ) scanf("%lld", a + i);
scanf("%lld%lld%lld%lld", &m, &p1, &s1, &s2);
LL dragon = 0, tiger = 0;
for (int i = 1; i < m; i ++ )
{
if (i == p1)
dragon += (a[i] + s1) * (m - i);
else
dragon += a[i] * (m - i);
}
for (int i = m + 1; i <= n; i ++ )
{
if (i == p1)
tiger += (a[i] + s1) * (i - m);
else
tiger += a[i] * (i - m);
}
if (dragon == tiger)
printf("%lld\n", m);
else if (dragon > tiger)
{
LL res = dragon - tiger;
int ans = m;
for (int i = 0; i <= n - m; i ++ )
{
LL temp = res;
if(i) res -= s2;
if (abs(temp) >= abs(res)) ans = m + i;
else break;
}
printf("%lld\n", ans);
}
else
{
LL res = tiger - dragon;
int ans = m;
for (int i = 0; i <= m - 1; i ++ )
{
LL temp = res;
if(i) res -= s2;
if (abs(temp) >= abs(res)) ans = m - i;
else break;
}
printf("%lld\n", ans);
}
return 0;
}
思路2:
我们按照前m-1个权值为正后n - m个权值为负将1到n所有势力值加到一起是sum。
然后从1到n遍历一遍,判断插入后sum的绝对值相较于上一次有没有减小,有的话说明答案更优,更新ans。这样还可以保证如果有比较恶心的样例(例如3 111 231)就不会被卡了。
最后记得,一定开long long。
AC CODE 2
#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;
typedef long long LL;
const int N = 100010;
LL a[N];
LL m, p1, s1, s2;
LL sum;
int n;
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i ++ ) scanf("%lld", a + i);
scanf("%lld%lld%lld%lld", &m, &p1, &s1, &s2);
a[p1] += s1;
for (int i = 1; i <= n; i ++ ) sum += a[i] * (m - i);
LL res = abs(sum), ans = m;
for (int i = 1; i <= n; i ++ )
{
LL temp = abs(s2 * (m - i) + sum);
if (temp <res) res = temp, ans = i;
}
printf("%lld\n", ans);
return 0;
}