亞馬遜網(wǎng)官網(wǎng)首頁四川seo平臺
一、心路歷程
這一個題目寫了三天,可以說是非常掙扎了,明明是例題,但是就是倔強著不去看書上的題解,WA了7次,TLE了4次。
?寫了不知道多少條測試用例,一遍一遍的過,一點一點的調(diào)試。
?最后終于找到了規(guī)則
二、思路
1、題目要求1到N,必須按照順序排,那么我們就可以認為 對每個 i >1,存在 i -1 到 i?的 0 的斥力
2、我們每一條A到B的排斥力P,看作B到A引力力 P * (-1)
3、規(guī)則1中 斥力,和 輸入的斥力,都按照第二條規(guī)則,轉(zhuǎn)化引力,然后不考慮斥力
4、用 BellmanFord算法,對轉(zhuǎn)換成的和輸入的引力集合,判斷是否存在負圈,存在直接輸出-1
5、不存在負圈,則直接對轉(zhuǎn)換成的和輸入的引力集合使用dijkstra算法,起點是1,如果d[N]大于1000000007(每條邊最大值乘以邊數(shù),加7是為了防止邊界出錯),則輸出-2,否則輸出d[N]。
三、代碼
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct Node
{int from, to, cost;Node(int from = 0, int to = 0, int cost = 0) : from(from), to(to), cost(cost) {}
};
vector<Node> nodes;
typedef pair<int, int> P;
vector<P> edges[1007];
int d[1007], N, inf = 0x3f3f3f3f, ML, MD, area[1007][1007];
bool used[1007];
void input()
{int from, to, cost;for (int i = 1; i <= ML; i++){scanf("%d%d%d", &from, &to, &cost);edges[from].push_back(P(cost, to));nodes.push_back(Node(from, to, cost));}for (int i = 1; i <= MD; i++){scanf("%d%d%d", &from, &to, &cost);edges[to].push_back(P(-cost, from));nodes.push_back(Node(to, from, -cost));}for (int i = 2; i <= N; i++){edges[i].push_back(P(0, i - 1));nodes.push_back(Node(i, i - 1, -1));}
}
bool bellmanFord(int s)
{bool flag = false;for (int i = 1; i <= N; i++){d[i] = inf;}d[s] = 0;for (int i = 1; i <= N; i++){for (int j = 0; j < nodes.size(); j++){if (d[nodes[j].from] + nodes[j].cost < d[nodes[j].to]){d[nodes[j].to] = d[nodes[j].from] + nodes[j].cost;if (i == N){flag = true;}}}}return flag;
}
void dijkstra(int s)
{for (int i = 1; i <= N; i++){d[i] = inf;used[i] = false;}d[s] = 0;priority_queue<P, vector<P>, greater<P>> que;que.push(P(0, s));while (!que.empty()){P current = que.top();que.pop();if (used[current.second] || current.first > d[current.second]){continue;}for (int i = 0; i < edges[current.second].size(); i++){P toEdge = edges[current.second][i];if (d[current.second] + toEdge.first < d[toEdge.second]){d[toEdge.second] = toEdge.first + d[current.second];que.push(P(d[toEdge.second], toEdge.second));}}}
}
void solve()
{if (bellmanFord(1)){printf("%d\n", -1);}else{dijkstra(1);if (d[N] > 1000000007){printf("%d\n", -2);}else{printf("%d\n", d[N]);}}
}
int main()
{scanf("%d%d%d", &N, &ML, &MD);input();solve();return 0;
}
?