题目描述
Tyvj已经一岁了,网站也由最初的几个用户增加到了上万个用户,随着Tyvj网站的逐步壮大,管理员的数目也越来越多,现在你身为Tyvj管理层的联络员,希望你找到一些通信渠道,使得管理员两两都可以联络(直接或者是间接都可以)。Tyvj是一个公益性的网站,没有过多的利润,所以你要尽可能的使费用少才可以。
目前你已经知道,Tyvj的通信渠道分为两大类,一类是必选通信渠道,无论价格多少,你都需要把所有的都选择上;还有一类是选择性的通信渠道,你可以从中挑选一些作为最终管理员联络的通信渠道。数据保证给出的通行渠道可以让所有的管理员联通。
输入格式
第一行n,m表示Tyvj一共有n个管理员,有m个通信渠道
第二行到m+1行,每行四个非负整数,p,u,v,w 当p=1时,表示这个通信渠道为必选通信渠道;当p=2时,表示这个通信渠道为选择性通信渠道;u,v,w表示本条信息描述的是u,v管理员之间的通信渠道,u可以收到v的信息,v也可以收到u的信息,w表示费用。
输出格式
最小的通信费用
样例:
5 6
1 1 2 1
1 2 3 1
1 3 4 1
1 4 1 1
2 2 5 10
2 2 5 5
9
提示
样例解释:
1-2-3-4-1存在四个必选渠道,形成一个环,互相可以到达。需要让所有管理员联通,需要联通2和5号管理员,选择费用为5的渠道,所以总的费用为9
注意:
U,v之间可能存在多条通信渠道,你的程序应该累加所有u,v之间的必选通行渠道
数据范围:
对于30%的数据,n<=10 m<=100
对于50%的数据, n<=200 m<=1000
对于100%的数据,n<=2000 m<=10000
#include<bits/stdc++.h>
using namespace std; using ll = long long;
int dir[4][2] = { 1, 0, -1, 0, 0, 1, 0, -1 };
//using lll = __int128; template <class T> istream& read(T& x, istream& cin = std::cin) { T num = 0; bool f = 0; char ch = 0; while (!isdigit(ch)) { f |= ch == '-'; if (!cin.get(ch)) return cin; }while (isdigit(ch)) { num = (num << 3) + (num << 1) + (ch ^ 48); if (!cin.get(ch)) break; }x = f ? -num : num; return cin; }template <class T> ostream& write(T x, ostream& cout = std::cout) { if (x < 0) cout.put('-'), x = -x; if (x > 9) write(x / 10); cout.put(x % 10 + '0'); return cout; }ostream& operator<<(ostream& cout, lll x) { write(x); return cout; }istream& operator>>(istream& cin, lll& x) { return read(x); }bool check(int i, int j);
bool check(int i, int j);
const int N = 1e5 + 10, mod = 1e9 + 7, INF = 0x3f3f3f3f;
int n, m, f[N], ans, cnt;
class Edge {
public:
int x, y, d;
bool operator>(const Edge& t) const {
return d > t.d;
}
};
priority_queue<Edge, vector<Edge>, greater<Edge>> edges;
int getf(int x) {
return x == f[x] ? x : f[x] = getf(f[x]);
}
bool merge(int u, int v) {
int t1 = getf(u), t2 = getf(v);
if (t1 == t2) return false;
if (t1 > t2) swap(t1, t2);
f[t2] = t1;
return true;
}
void init() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
f[i] = i;
}
while (m--) {
int tp, x, y, z;
cin >> tp >> x >> y >> z;
if (tp == 2)
edges.emplace(x, y, z);
else {
ans += z;
cnt += merge(x, y);
}
}
return;
}
void kruskal() {
while (edges.size()) {
auto [x, y, d] = edges.top();
edges.pop();
if (merge(x, y)) {
ans += d;
cnt++;
}
if (cnt == n - 1) return;
}
}
void solve() {
kruskal();
cout << ans;
return;
}
int main(void) {
ios::sync_with_stdio(0); cin.tie(0); cout << setprecision(6) << fixed;
int TT = 1;
//cin >> TT;
for (int ii = 1; ii <= TT; init(), solve(), ii++, cout << "\n") {}
return 0;
}