HihoCoder - 1077(拓扑排序,模板)

代码:

#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:
	vector<node>a;
	int edge_num, node_num;
public:
	Graph();
	Graph(int node_num);
	void addEdge(int s_node, int t_node);
	vector<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 + 1);
	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++;
}
vector<int> Graph::getAns() { // 拓扑排序
	vector<int> ret;
	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()];
		ret.push_back(q.front());
		q.pop();
		for (int i = 0; i < now.u.size(); i++) {
			a[now.u[i]].in_degree--;
			if (a[now.u[i]].in_degree == 0) {
				q.push(now.u[i]);
			}
		}
	}
	return ret;
}

int main() {
	int T;
	cin >> T;
	while (T--) {
		int n, m;
		cin >> n >> m;
		Graph ans = Graph(n);
		while (m--) {
			int s, t;
			cin >> s >> t;
			ans.addEdge(s, t);
		}
		if (ans.getAns().size() == n) {
			cout << "Correct" << endl;
		}
		else {
			cout << "Wrong" << endl;
		}
	}

}
发布了227 篇原创文章 · 获赞 142 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_36306833/article/details/102903752