368. 银河

// temp1111.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

/*
https://www.acwing.com/file_system/file/content/whole/index/content/3919/


银河中的恒星浩如烟海,但是我们只关注那些最亮的恒星。
我们用一个正整数来表示恒星的亮度,数值越大则恒星就越亮,恒星的亮度最暗是 1。

现在对于 N 颗我们关注的恒星,有 M 对亮度之间的相对关系已经判明。

你的任务就是求出这 N 颗恒星的亮度值总和至少有多大。

输入格式
第一行给出两个整数 N 和 M。

之后 M 行,每行三个整数 T,A,B
,表示一对恒星 (A,B) 之间的亮度关系。恒星的编号从 1 开始。

如果 T=1,说明 A 和 B 亮度相等。
如果 T=2,说明 A 的亮度小于 B 的亮度。
如果 T=3,说明 A 的亮度不小于 B 的亮度。
如果 T=4,说明 A 的亮度大于 B 的亮度。
如果 T=5,说明 A 的亮度不大于 B 的亮度。

输出格式
输出一个整数表示结果。

若无解,则输出 −1。

数据范围
N≤100000,M≤100000

输入样例:
5 7
1 1 2
2 3 2
4 4 1
3 4 5
5 4 5
2 3 5
4 5 1
输出样例:
11
*/



#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 100010, M = 400010;
int h[N], hs[N], e[M], ne[M], w[M], idx;
int dist[N];
int id[N],sz[N], low[N], dfn[N], stk[N], top,timestamp,scc_cnt;
bool in_stk[N];
int n, m;


void add(int h[], int a, int b, int c) {
	e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}


void tarjan(int u) {
	dfn[u] = low[u] = ++timestamp;
	stk[++top] = u, in_stk[u] = true;
	for (int i = h[u]; i != -1; i = ne[i]) {
		int j = e[i];
		if (!dfn[j]) {
			tarjan(j);
			low[u] = min(low[u], low[j]);
		}
		else if (in_stk[j]) low[u] = min(low[u], dfn[j]);
	}

	if (dfn[u] == low[u]) {
		++scc_cnt;
		int y;
		do {
			y = stk[top--];
			in_stk[y] = false;
			id[y] = scc_cnt;
			sz[scc_cnt]++;
		} while (y != u);
	}
}


int main()
{
	//两个图链 一个原图 一个连通分量图
	memset(h, -1, sizeof h);
	memset(hs, -1, sizeof hs);
	cin >> n >> m;
	while (m--) {
		//求最小值  使用>= 求最长路
		int t, a, b; cin >> t >> a >> b;
		if (t == 1) {
			add(h, a, b, 0); add(h,b, a, 0);
		}
		else if (t == 2) {
			//a<b b>=a+1
			add(h, a, b, 1);
		}
		else if (t == 3) {
			//a>=b
			add(h, b, a, 0);
		}
		else if (t == 4) {
			//a>b a>=b+1
			add(h, b, a, 1);
		}
		else if (t == 5) {
			//a<=b  b>=a
			add(h, a, b, 0);
		}
	}

	//超级源点
	for (int i = 1; i <= n; i++) {
		// i>=0+1
		add(h, 0, i, 1);
	}

	//求联通分量
	tarjan(0);

	int success = 1;
	//遍历每个边 若便在同一个连通分量中,则边不应该为正 否则有正环 无解
	//若两点不在同一个连通分量中,  则连接两个连通分量
	for (int i = 0; i <= n; i++) {
		for (int j = h[i]; j != -1; j = ne[j]) {
			int k = e[j];
			int a = id[i], b = id[k];
			if (a == b) {
				if (w[j] > 0) {
					success = 0;
					break;
				}
			}
			else {
				add(hs, a, b, w[j]);
			}
		}
		if (!success)break;
	}

	if (!success) {
		cout << -1 << endl;
	}
	else {
		//连通分量本身具有拓扑序(逆序)  所以逆序DAG的最长路
		long long res = 0;
		for (int i = scc_cnt; i >= 0; i--) {
			for (int j = hs[i]; j != -1; j = ne[j]) {
				int k = e[j];
				dist[k] = max(dist[k], dist[i] + w[j]);
			}
		}
		//每个连通分量的最长路得到, 那么每个连通分量的点数目乘以连通分量的最长距离(最小值) 就是最小值之和
		for (int i = 0; i <= scc_cnt; i++) {
			res += (long long)dist[i] * sz[i];
		}

		cout << res << endl;
	}



	return 0;
}

posted on 2025-08-08 11:01  itdef  阅读(11)  评论(0)    收藏  举报

导航