第八章的题都是掌握了算法思路就能做出来的,编程上难度不大。(间接导致了写题解花的时间比做题还长。。)
这个题如果不考虑效率的话,简单的枚举起点就可以了(但是在UVa估计会TLE?)
Rujia给了很好的提示:如果从 a 点出发,到 c 点会跪,那么从 a 到 c 之间的任何点出发,都会跪在 c 点上。
自己做题的时候,要如何想出这样精妙的结论呢?我觉得可以在简单的暴力枚举的时候,对于每个起点,打印一下在哪个点会跪,这样就很容易发现这个规律了。探索每道题目里隐含的规律(也是Rujia在第八章开篇时说到的),可以提升算法的效率。
这个也很好证明:
从 a 点到 a-c 间的任意点 b 之前,油箱里剩余的的油 >= 0。而从 b 出发时,油箱里的油 == 0。因此更没有可能通过 c 点。因此可以排除 a-c 间的所有点,直接从 c 继续枚举。
Run Time: 0.259s
#define UVa "LT8-13.11093.cpp"
char fileIn[30] = UVa, fileOut[30] = UVa;
#include<cstring>
#include<cstdio>
using namespace std;
//Global Variables. Reset upon Each Case!
const int maxn = 100001 + 10;
int N, T;
long long q[maxn], p[maxn];
/////
int possible(int x) {
long long tank = 0L;
for(int i = 0; i < N; i ++) {
tank += p[(i+x)%N];
tank -= q[(i+x)%N];
if(tank < 0) return i+x;
}
return -1; //-1 for success.
}
int main() {
scanf("%d", &T);
for(int kase = 1; kase <= T; kase ++) {
scanf("%d", &N);
for(int i = 0; i < N; i ++) scanf("%d", &p[i]);
for(int i = 0; i < N; i ++) scanf("%d", &q[i]);
printf("Case %d: ", kase);
int x, ok = 0;
for(x = 0; x < N; x ++) {
int ans = possible(x);
if(ans == -1) { //success
printf("Possible from station %d\n", x+1);
ok = 1;
break;
}
else {
if(ans >= N) break;
}
}
if(!ok) printf("Not possible\n");
}
return 0;
}