传送门:CodeForces-1341E
思路分析
这dis[i][j]表示表示到了第i个位置,距离上次等红灯后走了j秒所需要的最小等红绿灯次数
这就是一个01BFS的问题了,如果j=g的话就需要停留,次数就要+1,将新状态放到队尾,否则将新状态放到队首
没取出一个队首计算贡献,取min
样例输入
15 5
0 3 7 14 15
11 11
样例输出
45
AC代码
#include <functional>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <iomanip>
#include <vector>
#include <string>
#include <cstdio>
#include <chrono>
#include <random>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#if __cplusplus >= 201103L
#include <unordered_map>
#include <unordered_set>
#endif
#define ls x<<1
#define rs x<<1|1
#define fi first
#define se second
#define ll long long
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
bool IOerror=0;
inline char nc() {
static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
if(p1==pend) {
p1=buf;
pend=buf+fread(buf,1,BUF_SIZE,stdin);
if(pend==p1) {
IOerror=1;
return -1;
}
}
return *p1++;
}
inline bool blank(char ch) {
return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
}
template<class T> inline bool read(T &x) {
bool sign=0;
char ch=nc();
x=0;
for(; blank(ch); ch=nc());
if(IOerror)return false;
if(ch=='-')sign=1,ch=nc();
for(; ch>='0'&&ch<='9'; ch=nc())x=x*10+ch-'0';
if(sign)x=-x;
return true;
}
template<class T,class... U>bool read(T& h,U&... t) {
return read(h)&&read(t...);
}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int INF = 0x3f3f3f3f;
const int N=1e4+10;
int n,m,r,g,a[N];
int dis[N][1010],vis[N][1010];
int bfs() {
int ans=INF;
deque<pair<int,int>>q;
q.push_back(mp(0,0));
vis[0][0]=1;
while(!q.empty()) {
auto u=q.front();
q.pop_front();
int pos=u.fi;
int cost=u.se;
int need=n-a[pos]+cost;
if(need<=g) ans=min(ans,dis[pos][cost]*(r+g)+need);
if(cost==g) {
if(!vis[pos][0]) {
dis[pos][0]=dis[pos][g]+1;
vis[pos][0]=1;
q.push_back(mp(pos,0));
}
continue;
}
if(pos>1) {
int next=pos-1;
int need=a[pos]-a[next]+cost;
if(need<=g && !vis[next][need]) {
dis[next][need]=dis[pos][cost];
vis[next][need]=1;
q.push_front(mp(next,need));
}
}
if(pos<m) {
int next=pos+1;
int need=a[next]-a[pos]+cost;
if(need<=g && !vis[next][need]) {
dis[next][need]=dis[pos][cost];
vis[next][need]=1;
q.push_front(mp(next,need));
}
}
}
return ans==INF?-1:ans;
}
int main() {
#ifdef xiaofan
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
#endif
read(n,m);
for(int i=1; i<=m; i++) read(a[i]);
sort(a+1,a+1+m);
read(g,r);
printf("%d\n",bfs());
return 0;
}