Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //#define __GLIBCXX_DEBUG
- #include <bits/stdc++.h>
- using namespace std;
- #define rep(i, n) for(int i = 0; i < (int)(n); ++i)
- #define pb push_back
- #define ALL(a) (a.begin()), (a.end())
- #define mp make_pair
- #define F first
- #define S second
- #define SZ(a) ((int)(a.size()))
- typedef long long ll;
- typedef pair<int, int> PI;
- struct UF{
- vector<int> ap;
- UF(int n): ap(n){
- rep(i, n) ap[i] = i;
- }
- int find(int x){
- if(ap[x] == x)
- return x;
- return ap[x] = find(ap[x]);
- }
- void unit(int a, int b){
- ap[find(a)] = find(b);
- }
- };
- int n, m, k;
- vector<PI> aG[300], bG[300];
- void solve(){
- rep(i, n) aG[i].clear();
- rep(i, n) bG[i].clear();
- vector<pair<int, PI> > aed, bed;
- rep(i, m){
- int a, b, c;
- char ch;
- cin >> a >> b >> c >> ch;
- --a, --b;
- if(ch == 'A'){
- aed.pb(mp(c, mp(a, b)));
- aG[a].pb(mp(b, c));
- aG[b].pb(mp(a, c));
- }else{
- bed.pb(mp(c, mp(a, b)));
- bG[b].pb(mp(a, c));
- bG[a].pb(mp(b, c));
- }
- }
- vector<bool> usea(SZ(aed));
- vector<bool> useb(SZ(bed));
- sort(ALL(bed));
- sort(ALL(aed));
- UF uf(n);
- int cost = 0;
- rep(i, SZ(bed)){
- int a = bed[i].S.F;
- int b = bed[i].S.S;
- if(uf.find(a) == uf.find(b)) continue;
- uf.unit(a, b);
- useb[i] = 1;
- cost += bed[i].F;
- }
- int useaed = 0;
- rep(i, SZ(aed)){
- int a = aed[i].S.F;
- int b = aed[i].S.S;
- if(uf.find(a) == uf.find(b)) continue;
- uf.unit(a, b);
- usea[i] = 1;
- cost += aed[i].F;
- useaed += 1;
- }
- {
- bool ok = true;
- rep(i, n) ok &= uf.find(i) == uf.find(0);
- if(!ok || useaed > k){
- cout << -1 << endl;
- return;
- }
- }
- while(useaed < k){
- vector<pair<int, PI> > ap;
- rep(i, SZ(bed)){
- if(!useb[i]) continue;
- UF uf(n);
- rep(j, SZ(bed)){
- if(i == j || !useb[j]) continue;
- int a = bed[j].S.F;
- int b = bed[j].S.S;
- uf.unit(a, b);
- }
- rep(j, SZ(aed)){
- if(!usea[j]) continue;
- int a = aed[j].S.F;
- int b = aed[j].S.S;
- uf.unit(a, b);
- }
- rep(j, SZ(aed)){
- if(usea[j]) continue;
- int a = aed[j].S.F;
- int b = aed[j].S.S;
- if(uf.find(a) == uf.find(b)) continue;
- ap.pb(mp(aed[j].F - bed[i].F, mp(i, j)));
- break;
- }
- }
- if(ap.empty()) break;
- sort(ALL(ap));
- ++useaed;
- useb[ap[0].S.F] = false;
- usea[ap[0].S.S] = true;
- cost += ap[0].F;
- }
- if(useaed == k)
- cout << cost << endl;
- else
- cout << -1 << endl;
- }
- int main(int argc, char *argv[])
- {
- while(cin >> n >> m >> k && n) solve();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment