上一次用Floyd方法,这次采用dij方法做
更新ans的时候要连同人的小标一起,max函数用的时候要谨慎,WA了一次!!
#include <iostream>
#include <vector>
#include <map>
#include <list>
#include <set>
#include <deque>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cctype>
#include <cstdio>
#include <iomanip>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <queue>
using namespace std;
///宏定义
const int INF = 10000000;
const int MAXN = 310;
const int maxn = MAXN;
///全局变量 和 函数
///
struct Edge
{
int from;
int to;
int dist;
};
struct HeapNode
{
int u;
int d;
bool operator < (const HeapNode& rhs) const
{
return d > rhs.d;
}
};
struct Dijkstra
{
int n, m; //点数和边数
vector<Edge> edges; //边列表
vector<int> G[maxn]; //每个结点出发的边编号
bool done[maxn]; //是否已永久编号
int d[maxn]; //s到各个点的距离
// double d[maxn];
int p[maxn]; //最短路中的上一条边 (打印结果用)
void init(int n)
{
this->n = n;
for (int i = 0; i <= n; i++)
G[i].clear();
edges.clear();
}
void AddEdge(int from, int to, int dist)
{
Edge tmp;
tmp.from = from;
tmp.to = to;
tmp.dist = dist;
edges.push_back(tmp);
m = edges.size();
G[from].push_back(m - 1);
}
void dijkstra(int s)
{
priority_queue<HeapNode> Q;
for (int i = 0; i <= n; i++)
d[i] = INF;
d[s] = 0;
memset(done, 0, sizeof(done));
HeapNode tmp;
tmp.d = 0;
tmp.u = s;
Q.push(tmp);
while (!Q.empty())
{
HeapNode x = Q.top();
Q.pop();
int u = x.u;
if (done[u])
continue;
done[u] = true;
for (int i = 0; i < G[u].size(); i++)
{
Edge &e = edges[G[u][i]];
if (d[e.to] > d[u] + e.dist)
{
d[e.to] = d[u] + e.dist;
HeapNode temp;
temp.d = d[e.to];
temp.u = e.to;
Q.push(temp);
}
}
}
}
};
int n;
double posx[maxn];
double posy[maxn];
int main()
{
///变量定义
int i, j;
int cases = 1;
while (1)
{
scanf("%d", &n);
if (n == 0)
break;
Dijkstra dij;
dij.init(n);
for (i = 1; i <= n; i++)
{
int nums;
cin >> nums;
for (j = 0; j < nums; j++)
{
int towards, timecost;
cin >> towards >> timecost;
dij.AddEdge(i, towards, timecost);
}
}
int ans = INF;
int person;
for (i = 1; i <= n; i++)
{
dij.dijkstra(i);
int curans = -1;
for (j = 1; j <= n; j++)
{
if (dij.d[j] == INF)
{
curans = INF;
break;
}
curans = max(curans, dij.d[j]);
}
if (curans < INF)
{
if (ans > curans)
{
ans = curans;
person = i;
}
}
}
if (ans != INF)
{
printf("%d %d\n", person, ans);
}
else
printf("disjoint\n");
}
///结束
return 0;
}