问题 A: 关键路径
时间限制: 1 Sec 内存限制: 128 MB
献花: 23 解决: 9
[献花][花圈][TK题库]
题目描述
描述:
图的连接边上的数据表示其权值,带权值的图称作网。
上图可描述为顶点集为(a,b,c,d,e)
边集及其权值为(始点,终点 权值):a b 3
a c 2
b d 5
c d 7
c e 4
d e 6
网的源点是入度为0的顶点,汇点是出度为0的顶点。网的关键路径是指从源点到汇点的所有路径中,具有最大路径长度的路径。上图中的关键路径为a->c->d->e,其权值之和为关键路径的长度为15。
本题的要求是根据给出的网的邻接矩阵求该网的关键路径及其长度。
输入
第一行输入一个正整数n(1<=n<=5),其代表测试数据数目,即图的数目
第二行输入x(1<=x<=15)代表顶点个数,y(1<=y<=19)代表边的条数
第三行给出图中的顶点集,共x个小写字母表示顶点
接下来每行给出一条边的始点和终点及其权值,用空格相隔,每行代表一条边。
输出
第一个输出是图的关键路径(用给出的字母表示顶点, 用括号将边括起来,顶点逗号相隔)
第二个输出是关键路径的长度
每个矩阵对应上面两个输出,两个输出在同一行用空格间隔,每个矩阵的输出占一行。
样例输入
2
5 6
abcde
a b 3
a c 2
b d 5
c d 7
c e 4
d e 6
4 5
abcd
a b 2
a c 3
a d 4
b d 1
c d 3
样例输出
(a,c) (c,d) (d,e) 15
(a,c) (c,d) 6
注意点:
- 输出关键路径的时候,不能按照节点的从小到大一次枚举,而是一条线顺着遍历下去
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cfloat>
#include <iomanip>
#include <map>
#include <functional>
#define INF INT32_MAX
using namespace std;
typedef struct node
{
int v;
int w;
node(int _v, int _w) :v(_v), w(_w) {};
}Node;
const int MaxN = 20;
int InDegree[MaxN] = { 0 };
stack<int> SQsort;
vector<Node>G[MaxN];
int ve[MaxN], vl[MaxN];
string vex;
int N;
bool TopSort()
{
fill(ve, ve + N, 0);
fill(InDegree, InDegree + N, 0);
queue<int> que;
for (int i = 0; i < N; ++i)
{
for (int k = 0; k < G[i].size(); ++k)
++InDegree[G[i][k].v];
}
for (int i = 0; i < N; ++i)
{
if (!InDegree[i])
que.push(i);
}
while (que.size())
{
int u = que.front(); que.pop(); SQsort.push(u);
for (int k = 0; k < G[u].size(); ++k)
{
int v = G[u][k].v, w = G[u][k].w;
if (!(--InDegree[v]))
que.push(v);
if (ve[v] < ve[u] + w)
ve[v] = ve[u] + w;
}
}
if (SQsort.size() != N) return false;
return true;
}
int CriticalPath()
{
if (TopSort() == false)return -1;
fill(vl, vl + N, ve[N - 1]);
while (SQsort.size())
{
int u = SQsort.top(); SQsort.pop();
for (int i = 0; i < G[u].size(); ++i)
{
int v = G[u][i].v, w = G[u][i].w;
if (vl[u] > vl[v] - w)
vl[u] = vl[v] - w;
}
}
int u = 0;
while (u < N)
{
bool flag = false;
for (int i = 0; i < G[u].size(); ++i)
{
int v = G[u][i].v, w = G[u][i].w;
if (ve[u] == vl[v] - w)
{
cout << "(" << vex[u] << "," << vex[v] << ") ";
u = v; flag = true;
continue;
}
}
if(!flag)++u;
}
cout << ve[N - 1];
return ve[N - 1];
}
int Getid(char ch)
{
return vex.find(ch);
}
int main()
{
#ifdef _DEBUG
freopen("data.txt", "r+", stdin);
#endif // _DEBUG
std::ios::sync_with_stdio(false);
int M,L;
char uc, vc;
int u, v, w;
while(cin >> M)
{
while (M--)
{
cin >> N >> L >> vex;
for (int i = 0; i < N; ++i)G[i].clear();
while (L--)
{
cin >> uc >> vc >> w;
u = Getid(uc), v = Getid(vc);
G[u].push_back(node(v, w));
}
if (N == 1)
{
cout << "(" << vex[0] << "," << vex[0] << ") " << 0;
}
CriticalPath(); cout << endl;
}
}
return 0;
}
/**************************************************************
Problem: 23132
User: Sharwen
Language: C++
Result: 升仙
Time:0 ms
Memory:1712 kb
****************************************************************/