好吧,
終於可以緩解下這兩天的想砍人的情緒了。開始錯了之後就跟別人討論——以爲是數據變態(後來某某學長的一句話更是令我們崩潰):這個小偷能
瞬間移動 or 讓時光倒流....(有點科幻了)。糾結了半天發先不是這個問題,因爲標程都跑不出這些數據來。
最後發現是沒加代碼中的“紅色部分”了(去掉這個,pcnt數組就亂了,除了起點之外,各個點的pcnt都會在求最短路徑裏被初始化):
我喜歡偷懶,喜歡用一些隱含的條件。比如初始化啦,還有這個函數遞歸邊界啦,能不指出就不指出。
好了,於是乎。。各種悲劇。
[cpp] view
plaincopyprint?
- //太恐怖了,發現之前貼上的代碼求最短路徑時多加了個循環
- //現在改回來了,時間頓時少了400ms多。
- #include <cstdio>
- #include <queue>
- #include <algorithm>
- using namespace std;
- const int INF = 10000002;
- const int MAXN = 1002;
- int g[MAXN][MAXN], vis[MAXN], dis[MAXN], isPath[MAXN], par[MAXN][MAXN], pcnt[MAXN];
- typedef pair<int, int> pii;
- priority_queue<pii, vector<pii>, greater<pii> > q;
- void dijkstra(int n, int s) {
- fill(vis+1, vis+n+1, 0);
- for(int i = 1; i <= n; i++) {
- dis[i] = INF;
- }
- dis[s] = 0;
- q.push(make_pair(dis[s], s));
- while(!q.empty()) {
- pii u = q.top();
- q.pop();
- int x = u.second;
- if(vis[x]) continue;
- vis[x] = 1;
- for(int y = 1; y <= n; y++) {
- if(!vis[y] && g[x][y]) {
- if(dis[y] > dis[x] + g[x][y]) { //除了起點外,所有的點都執行這快代碼
- dis[y] = dis[x]+g[x][y];
- pcnt[y] = 1;
- par[y][0] = x;
- q.push(make_pair(dis[y], y));
- }
- else if(dis[y] == dis[x] + g[x][y]){
- par[y][pcnt[y]++] = x;
- }
- }
- }
- }
- }
- void buildPar(int t, int s) {
- isPath[t] = 1;
- if(t == s) {
- return;
- }
- for(int i = 0; i < pcnt[t]; i++) {
- int x = par[t][i];
- if(!isPath[x]) {
- buildPar(x, s);
- }
- }
- return;
- }
- void buildRoute(int t, int s, int n) {
- //fill(pcnt+1, pcnt+n+1, 0);
- fill(isPath+1, isPath+n+1, 0);
- buildPar(t, s);
- }
- void query(int s, int qt, int &ans, int n) {
- for(int i = 1; i <= n; i++) {
- if(isPath[i]) {
- if(dis[i] == qt) {
- ans++;
- }
- else if(dis[i] > qt) {
- for(int j = 0; j < pcnt[i]; j++) {
- int t = par[i][j];
- if(dis[t] < qt){
- ans++;
- }
- }
- }
- }
- }
- }
- int main() {
- int n, m, s, t, u, v, w, q, qt, cas = 0;
- while(scanf("%d%d%d%d", &n, &m, &s, &t) != EOF) {
- if(cas) {
- printf("/n");
- }
- else {
- cas = 1;
- }
- fill(g[1], g[n+1], 0);
- for(int k = 0; k < m; k++) {
- scanf("%d%d%d", &u, &v, &w);
- g[u][v] = g[v][u] = w;
- }
- dijkstra(n, s);
- buildRoute(t, s, n);
- scanf("%d", &q);
- for(int i = 0; i < q; i++) {
- scanf("%d", &qt);
- if(qt >= dis[t] || qt <= 0) {
- printf("1/n");
- continue;
- }
- int ans = 0;
- query(s, qt, ans, n);
- printf("%d/n", ans);
- }
- }
- return 0;
- }