P2662 牛场围栏(同余最短路)

P2662 牛场围栏

思路

假设我们已经知道同余最短路是什么了,这里就不再过多赘述。

我们要尽可能地得到更多地课建成地边,那么我们必然要选一个 b a s e base 相对小的,因此我们可以对所有的棍子排个序,然后取 a [ 1 ] m a[1] - m 作为我们选取的 b a s e base

接下来就是考虑建边了,参考这篇博客,我们对所有的可能的边都建立一条与 b a s e base 同余的边,即

for(int i = 1; i < n; i++)
    for(int j = 0; j < base; j++)
        for(int k = a[i] - m; k <= a[i]; k++)
            add(j, (j + k) % base, k)// from, to, value;

接下来就是跑一遍 s p f a d i j k s t r a spfa||dijkstra ,得到我们的 d i s dis 数组。这里我再说明一下 d i s dis 数组的含义:

e g . d i s [ i ] = x eg. dis[i] = x 表示的是 x i ( m o d b a s e ) x \equiv i \pmod {base} x x 是满足要求的最小值。

所以当进行答案的统计的时候,如果发现有 d i s dis 数组没有被访问过,说明有若干同余的围栏是不可能得到的,这个时候没有最大值。否则的话,我们的答案将会是,所有 d i s dis 数组中 d i s b a s e dis - base 的最大值,原因就在上面 d i s dis 数组所讲诉的含义。

代码

/*
  Author : lifehappy
*/
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define mp make_pair
#define pb push_back
#define endl '\n'

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;

const double pi = acos(-1.0);
const double eps = 1e-7;
const int inf = 0x3f3f3f3f;

inline ll read() {
  ll f = 1, x = 0;
  char c = getchar();
  while(c < '0' || c > '9') {
    if(c == '-')    f = -1;
    c = getchar();
  }
  while(c >= '0' && c <= '9') {
    x = (x << 1) + (x << 3) + (c ^ 48);
    c = getchar();
  }
  return f * x;
}

void print(ll x) {
  if(x < 10) {
    putchar(x + 48);
    return ;
  }
  print(x / 10);
  putchar(x % 10 + 48);
}

const int N = 3e3 + 10;

int n, m, a[N];

bool visit[N];

ll dis[N];
vector<pii> G[N];

void spfa() {
  memset(dis, 0x3f, sizeof dis);
  queue<int> q;
  q.push(0);
  visit[0] = 1, dis[0] = 0;
  while(q.size()) {
    auto temp = q.front();
    q.pop();
    visit[temp] = 0;
    for(auto i : G[temp]) {
      if(dis[i.first] > dis[temp] + i.second) {
        dis[i.first] = dis[temp] + i.second;
        if(!visit[i.first]) {
          q.push(i.first);
          visit[i.first] = 1;
        }
      }
    }
  }
}

int main() {
  // freopen("in.txt", "r", stdin);
  // freopen("out.txt", "w", stdout);
  // ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  n = read(), m = read();
  for(int i = 1; i <= n; i++) a[i] = read();
  sort(a + 1, a + 1 + n);
  if(a[1] - m <= 1) {
    puts("-1");
    return 0;
  }
  int base = a[1] - m;
  for(int i = 1; i <= n; i++) {
    for(int j = 0; j < base; j++) {
      for(int k = a[i] - m; k <= a[i]; k++) {
        G[j].pb(mp((j + k) % base, k));
      }
    }
  }
  spfa();
  ll ans = 0;
  for(int i = 1; i < base; i++) {
    if(dis[i] == 0x3f3f3f3f3f3f3f3f) {
      puts("-1");
      return 0;
    }
    ans = max(ans, dis[i] - base);
  }
  cout << ans << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45483201/article/details/107448568
今日推荐