HihoCoder - 1175 topological sorting Diethylene

Analysis of ideas:

Because the flow is constant, the flow directly val val each node as a last flow.
Mainly to familiarize yourself with how to write CLASS.

Code:

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

struct node
{
	vector<int>u;//出边
	int val, in_degree;
	node() {
		val = in_degree = 0;
		u.clear();
	}
};
class Graph
{
private:
	static const int MOD = 142857;
	vector<node>a;
	int edge_num, node_num;
public:
	Graph();
	Graph(int node_num);
	void addEdge(int s_node, int t_node);
	void addNodeVal(int node_index, int val);
	int getAns();
};
Graph::Graph() {
	this->a.clear();
	this->edge_num = this->node_num = 0;
}
Graph::Graph(int node_num) {
	a.clear();
	a.resize(node_num+5);
	this->node_num = node_num ;
	this->edge_num = 0;
}
void Graph::addEdge(int s_node, int t_node) {
	this->a[s_node].u.push_back(t_node);
	this->a[t_node].in_degree++;
	this->edge_num++;
}
void Graph::addNodeVal(int node_index, int val) {
	this->a[node_index].val = (this->a[node_index].val + val) % MOD;
}
int Graph::getAns() { // 拓扑排序
	int ret = 0;
	queue<int>q;
	for (int i = 1; i <= node_num; i++) {
		if (a[i].in_degree == 0) {
			q.push(i);
		}
	}
	while (!q.empty()) {
		node& now = a[q.front()];
		q.pop();
		ret = (ret + now.val) % MOD;
		for (int i = 0; i < now.u.size(); i++) {
			a[now.u[i]].in_degree--;
			a[now.u[i]].val = (a[now.u[i]].val + now.val) % MOD;
			if (a[now.u[i]].in_degree == 0) {
				q.push(now.u[i]);
			}
		}
	}
	return ret;
}
int main()
{
	int n, m, k;
	while (cin >> n >> m >> k) {
		Graph g = Graph(n);
		while (k--) {
			int x;
			cin >> x;
			g.addNodeVal(x, 1);
		}
		while (m--) {
			int node_s, node_t;
			cin >> node_s >> node_t;
			g.addEdge(node_s, node_t);
		}
		cout << g.getAns() << endl;
	}
}
Published 227 original articles · won praise 142 · views 90000 +

Guess you like

Origin blog.csdn.net/qq_36306833/article/details/102845611
Recommended