您的位置:首页 > 理论基础 > 数据结构算法

中国大学MOOC-数据结构基础习题集、06-4、How Long Does It Take

2015-01-10 23:49 513 查看
题目链接:http://www.patest.cn/contests/mooc-ds/06-4

题目分析:这是一道考察图的拓扑排序问题,输入是图的相关信息,输出最早结束时间或者Impossible。题目还是比较简单的。

特别说明:

  1. 输出最大值,可以用标准库的函数:max_element,返回值是地址,所以需要*把内容取出来。如数组a
,最大值为:*max_element(earlist, earlist+n)。当然不是求数组的最大值,而是求vector的最大值,只需要传相应的迭代器就可以。

  2. 同理,两者之中想求得最大值,可以直接max(a, b)返回的就是最大值了,当然注意不同类型的不能比较哦(除非重载过<)。

  3. 如果case2错误的话,注意earlist最大的,不一定是最后一个,要输出max_element(earlist, earlist+n),而不是earlist[n-1]。

  4. 如果case4错误的话,关注一下本代码64行,看看是不是忘记用max函数了(或者其他等价的函数)。

  earlist[W] = max(earlist[W], earlist[V] + vec[i].l); 


代码分析:

  头文件及结构体声明:1~15

  cmp函数(用于sort排序函数的子函数)16~20

  最早完成时间、入度数组的动态申请及初始化:21~33

  每个活动的s,e,l的输入处理:34~43

  sort函数用于排序,把终点相同的活动集中在一起:44

  拓扑排序:45~71

  判断是否存在回路并输出结果:72~81

  

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

struct node
{
int s;
int e;
int l;
node(int a, int b, int c):s(a), e(b), l(c) {}
};

int cmp(const node &a, const node &b)
{
return a.e < b.e;
}

int main()
{
int n, m;
cin >> n >> m;
int *earlist = new int
;
int *Indegree = new int
;

for(int i=0; i<n; i++)
{
Indegree[i] = 0;
earlist[i] = 0;
}

vector<node> vec;

for(int i=0; i<m; i++)
{
int a, b, c;
cin >> a >> b >> c;
Indegree ++;
vec.push_back(node(a, b, c));
}

sort(vec.begin(), vec.end(), cmp);

queue<int> Q;

for(int V=0; V<n; V++)
if ( Indegree[V] == 0)
Q.push(V);

int cnt = 0;

while( Q.size() != 0)
{
int V = Q.front();
Q.pop();
cnt++;
for ( int i=0; i<m; i++ )
{
if ( vec[i].s == V)
{
int W = vec[i].e;
earlist[W] = max(earlist[W], earlist[V] + vec[i].l);
if ( --Indegree[W] == 0)
Q.push(W);
}
}

}

if ( cnt != n )
{
cout << "Impossible" << endl;
}
else
{
cout << *max_element(earlist, earlist+n) << endl;
}
return 0;
}


[b]AC成果:




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: