把状态为1的权重都改为0,之后prim()就可以了。
#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 105;
const int INF = 1<<8;
struct Node{
int vex, weight, state;
Node(int _vex = 0, int _weight = 0, int _state = 0):vex(_vex),weight(_weight),state(_state){}
};
vector<Node> G[maxn];
int n;
bool intree[maxn];
int mindist[maxn];
void Init(){
for(int i = 0; i < maxn; i++){
G[i].clear() ;
intree[i] = false;
mindist[i] = INF;
}
}
int prim(int s){
int ans = 0;
int addNode, tempMin, ves;
intree[s] = true;
for(unsigned int i = 0; i < G[s].size(); i++){
ves = G[s][i].vex;
mindist[ves] = G[s][i].weight;
}
for(int nodeNum = 1; nodeNum <= n-1; nodeNum++){
tempMin = INF;
for(int i = 1; i <= n; i++){
if(intree[i] == false && mindist[i] < tempMin){
tempMin = mindist[i];
addNode = i;
}
}
intree[addNode] = true;
ans += tempMin;
for(int i = 0; i < G[addNode].size() ; i++ ){
ves = G[addNode][i].vex;
if(intree[ves] == false && G[addNode][i].weight < mindist[ves]){
mindist[ves] = G[addNode][i].weight;
}
}
}
return ans;
}
int main(){
int v1, v2, weight, state;
while(scanf("%d",&n) != EOF && n){
Init();
for(int i = 0; i < n*(n-1)/2; i ++){
scanf("%d%d%d%d",&v1, &v2, &weight, &state);
G[v1].push_back(Node(v2, weight, state));
G[v2].push_back(Node(v1, weight, state));
}
for(int i = 1; i <= n; i++){
for(int j = 0; j < G[i].size(); j++){
if(G[i][j].state == 1){
G[i][j].weight = 0;
}
}
}
int ans = prim(1);
printf("%d\n",ans);
}
return 0;
}