虽然编程测试没在规定时间内做出来,而且素质测试也凉透了,但是还是放一下后来打的代码,不知道能过多少样例。
问题描述
第一行输入两个数字,第一个代表系统个数,第二行代表系统之间的依赖关系。
然后输入每个系统的功耗,用空格隔开;最后输入各个系统之间的依赖关系。
需要计算出最大的耗时总量。(不记得是最长链还是最大耗时总量)
比如:
5 4
7 //1号系统耗时7ms
5 //2号系统耗时5ms
3 // ...
5
6
1 2 //1号系统依赖于2号系统
1 3 //1号系统依赖于3号系统
2 5 //2号系统依赖于5号系统
4 5 //4号系统依赖于5号系统
则依赖链有1->2->5, 1->3, 4->5
#include<iostream>
using namespace std;
class Solution {
public:
//深度优先算法求每条路径的总耗时,记录最大总耗时
void dfs(int **matrix, bool* visited, int* cost, int point, int count, int& costs, int& ans) {
if (!visited[point]) {
visited[point] = true;
for (int i = 1; i <= count; i++) {
if (i != point && !visited[i] && matrix[point][i]) {
costs += cost[i];
//记录最大耗时总量
if (ans < costs) ans = costs;
dfs(matrix, visited, cost, i, count, costs, ans);
costs -= cost[i];
}
}
}
}
void solution() {
int count_system, count_dep;
//输入系统数和依赖数
cin >> count_system >> count_dep;
//记录每个系统的耗时
int* cost = new int[count_system+1];
//记录依赖关系
int** matrix = new int*[count_system+1];
bool* visited = new bool[count_system + 1];
for (int i = 0; i < count_system+1; i++) {
matrix[i] = new int[count_system+1];
for (int j = 0; j < count_system+1; j++) {
matrix[i][j] = 0;
}
}
//输入耗时和依赖关系
for (int i = 1; i < count_system+1; i++) {
cin >> cost[i];
}
for (int i = 0; i < count_dep; i++) {
int start, end;
cin >> start >> end;
matrix[start][end] = 1;
}
int ans = 0;
for (int i = 0; i < count_system; i++) {
for (int i = 0; i < count_system + 1; i++) {
visited[i] = false;
}
dfs(matrix, visited, cost, i + 1, count_system, cost[i+1], ans);
}
cout << ans << endl;
}
};
int main() {
Solution s;
s.solution();
system("pause");
}
/**若求最长链的总耗时
**则算法如下
**原理与上面的相似
**/
class Solution2 {
public:
void dfs(int **matrix, bool* visited, int* cost, int point, int count, int length, int& longest, int costs, int& ans) {
if (!visited[point]) {
visited[point] = true;
for (int i = 1; i <= count; i++) {
if (i != point && !visited[i] && matrix[point][i]) {
costs += cost[i];
length += 1;
//记录最长链的耗时总量
if (longest < length) {
longest = length;
ans = costs;
}
dfs(matrix, visited, cost, i, count, length, longest, costs, ans);
costs -= cost[i];
}
}
}
}
void solution() {
int count_system, count_dep;
cin >> count_system >> count_dep;
int* cost = new int[count_system+1];
int** matrix = new int*[count_system+1];
bool* visited = new bool[count_system + 1];
for (int i = 0; i < count_system+1; i++) {
matrix[i] = new int[count_system+1];
visited[i] = false;
for (int j = 0; j < count_system+1; j++) {
matrix[i][j] = 0;
}
}
for (int i = 1; i < count_system+1; i++) {
cin >> cost[i];
}
for (int i = 0; i < count_dep; i++) {
int start, end;
cin >> start >> end;
matrix[start][end] = 1;
}
int ans = 0;
int length = 0;
for (int i = 0; i < count_system; i++) {
for (int i = 0; i < count_system + 1; i++) {
visited[i] = false;
}
dfs(matrix, visited, cost, i + 1, count_system, 0, length, cost[i + 1], ans);
}
cout << ans << endl;
}
};