Codeforces #676 (Div. 2) D. Hexagons
题目链接:https://codeforces.ml/contest/1421/problem/D
题意: 走到目的地,要求消耗最小。
题解:
第一行输入要输入的例子的个数,
第二行输入目的地的坐标(y,x)(个人习惯,横着增加的是x,竖着增加的是y)
第三行输入六个方向的消耗
求走过的路消耗最少。
下面以 (-3, 1) 为例子讲一下过程。
从(0, 0) 走到 (-3, 1) 可以通过走
C
3
C_3
C3 +
C
5
C_5
C5 或者
C
4
C_4
C4两种方向。因为消耗还不确定,所以不确定
C
3
C_3
C3 +
C
5
C_5
C5 和
C
4
C_4
C4的大小。所以要判断:两者之间的大小。
同理其他五个方向也是这样的。
即更新出 要走的方向的最小消耗值。(先更新六个方向的最小值)
c1 = min (c1, c2 + c6);
c2 = min (c2, c1 + c3);
c3 = min (c3, c2 + c4);
c4 = min (c4, c3 + c5);
c5 = min (c5, c4 + c6);
c6 = min (c6, c1 + c5);
再划分成 4 个板块(6个也可以):
第一种情况当目标位置在阴影位置:
即当 y >= 0 && x >= 0 时:
这里不用担心会重复。
(y - min(y, x)) × c6 + (x - min(y, x)) × c2;
如果最终走
C
2
C_2
C2方向,那么
C
6
C_6
C6 方向就为0,想一下,很简单的。
sum += min(y, x) * c1 + (y - min(y, x)) * c6 + (x - min(y, x)) * c2;
当 y >= 0 && x < 0时:
这里x小于0,所以 C 5 C_5 C5 要取负
sum += y * c6 + x * (-c5);
当 y < 0 && x >= 0时:
sum += y * c3 + x * (-c2);
这里y,x都小于0,所以
C
4
C_4
C4 要取负
当 y < 0 && x < 0 时:
sum += max(y, x) * (-c4) + (max(y, x) - y) * c3 + (max(y, x) - x) * c5;
完整代码如下:👇👇👇👇👇
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<algorithm>
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define ll long long
#define int ll
#define INF 0x3f3f3f3f
using namespace std;
int read()
{
int w = 1, s = 0;
char ch = getchar();
while (ch < '0' || ch>'9') { if (ch == '-') w = -1; ch = getchar(); }
while (ch >= '0' && ch <= '9') { s = s * 10 + ch - '0'; ch = getchar(); }
return s * w;
//最大公约数
}int gcd(int x,int y) {
if(x<y) swap(x,y);//很多人会遗忘,大数在前小数在后
//递归终止条件千万不要漏了,辗转相除法
return x % y ? gcd(y, x % y) : y;
}
int lcm(int x,int y)//计算x和y的最小公倍数
{
return x * y / gcd(x, y);//使用公式
}
//------------------------ 以上是我常用模板与刷题几乎无关 ------------------------//
signed main()
{
int t;
cin >> t;
while(t--) {
int y, x;
cin >> y >> x;
int c1,c2,c3,c4,c5,c6;
cin >> c1 >> c2 >> c3 >> c4 >> c5 >> c6;
c1 = min (c1, c2 + c6);
c2 = min (c2, c1 + c3);
c3 = min (c3, c2 + c4);
c4 = min (c4, c3 + c5);
c5 = min (c5, c4 + c6);
c6 = min (c6, c1 + c5);
int sum =0;
if (y >= 0 && x >= 0) {
sum += min(y, x) * c1 + (y - min(y, x)) * c6 + (x - min(y, x)) * c2;
}
else if (y >= 0 && x < 0) {
sum += y * c6 + x * (-c5);
}
else if (y <= 0 && x > 0) {
sum += y * c3 + x * (-c2);
}
else {
sum += max(y, x) * (-c4) + (max(y, x) - y) * c3 + (max(y, x) - x) * c5;
}
printf("%lld\n", abs(sum));
}
return 0;
}