Luogu P1821 [USACO07FEB]銀牛派對Silver Cow Party
P1821 [USACO07FEB]銀牛派對Silver Cow Party
題目描述
One cow from each of N farms (1 ≤ N ≤ 1000) conveniently numbered 1..N is going to attend the big cow party to be held at farm #X (1 ≤ X ≤ N). A total of M (1 ≤ M ≤ 100,000) unidirectional (one-way roads connects pairs of farms; road i requires Ti (1 ≤ Ti ≤ 100) units of time to traverse.
Each cow must walk to the party and, when the party is over, return to her farm. Each cow is lazy and thus picks an optimal route with the shortest time. A cow‘s return route might be different from her original route to the party since roads are one-way.
Of all the cows, what is the longest amount of time a cow must spend walking to the party and back?
寒假到了,N頭牛都要去參加一場在編號為X(1≤X≤N)的牛的農場舉行的派對(1≤N≤1000),農場之間有M(1≤M≤100000)條有向路,每條路長Ti(1≤Ti≤100)。
每頭牛參加完派對後都必須回家,無論是去參加派對還是回家,每頭牛都會選擇最短路徑,求這N頭牛的最短路徑(一個來回)中最長的一條路徑長度。
輸入輸出格式
輸入格式:
第一行三個整數N,M, X;
第二行到第M+1行:每行有三個整數Ai,Bi, Ti ,表示有一條從Ai農場到Bi農場的道路,長度為Ti。
輸出格式:
一個整數,表示最長的最短路得長度。
輸入輸出樣例
輸入樣例#1:
4 8 2 1 2 4 1 3 2 1 4 7 2 1 1 2 3 5 3 1 2 3 4 4 4 2 3
輸出樣例#1:
10
和我的另一篇題解大概一個思路,不再解釋,附上鏈接
http://www.cnblogs.com/bljfy/p/8835733.html
代碼
#include <iostream> #include <cstring> #include <cstdio> #include <queue> #define MAXN 100003 #define INF 123456789 using namespace std; int n, m, x, first[1008], next[MAXN], u[MAXN], v[MAXN], w[MAXN], dis[1008], ans[1008], Ans; queue<int> P; bool vis[1008]; void Shortest_Path_Faster_Algorithm(int s) { while(!P.empty()) { int t = P.front(); P.pop(); int k = first[t]; while(k != -1) { if(dis[v[k]] > dis[u[k]]+w[k]) { dis[v[k]] = dis[u[k]]+w[k]; if(vis[v[k]] == 0) {P.push(v[k]); vis[v[k]] = 1;} } k = next[k]; } vis[t] = 0; } } int main() { scanf("%d%d%d", &n, &m, &x); memset(first, -1, sizeof(first)); for(int i=1; i<=n; i++) {dis[i] = INF;} dis[x] = 0; P.push(x); for(int i=1; i<=m; i++) {scanf("%d%d%d", &u[i], &v[i], &w[i]); next[i] = first[u[i]]; first[u[i]] = i;} vis[x] = 1; Shortest_Path_Faster_Algorithm(x); for(int i=1; i<=n; i++) {if(dis[i] != INF) ans[i] += dis[i];} memset(vis, false, sizeof(vis)); memset(first, -1, sizeof(first)); memset(next, 0, sizeof(next)); for(int i=1; i<=n; i++) {dis[i] = INF;} dis[x] = 0; while(!P.empty()) {P.pop();} P.push(x); for(int i=1; i<=m; i++) {next[i] = first[v[i]]; first[v[i]] = i;} vis[x] = 1; swap(u, v); Shortest_Path_Faster_Algorithm(x); for(int i=1; i<=n; i++) {if(dis[i] != INF) ans[i] += dis[i]; Ans = max(Ans, ans[i]);} printf("%d", Ans); return 0; }
Luogu P1821 [USACO07FEB]銀牛派對Silver Cow Party