Time Limit: 5000MS | Memory Limit: 10000K | |
Total Submissions: 7356 | Accepted: 2555 |
Description
Input
Output
Sample Input
10 Alphonzo Bernardo 32 Alphonzo Park 57 Alphonzo Eduardo 43 Bernardo Park 19 Bernardo Clemenzi 82 Clemenzi Park 65 Clemenzi Herb 90 Clemenzi Eduardo 109 Park Herb 24 Herb Eduardo 79 3
Sample Output
Total miles driven: 183
Source
#include<iostream> #include<cstring> using namespace std; const int MAX_NV = 21; const int INF = 0x7f7f7f7f; typedef struct Edge { int sv,ev,w; }Edge; int nv; char name[MAX_NV][12]; int gam[MAX_NV][MAX_NV]; Edge mstEdge[MAX_NV]; int s; int ans; bool isCycle; int IndName(char ch[]) { int ind=0; while(ind<nv && strcmp(name[ind],ch)!=0) ind++; if(ind==nv) strcpy(name[nv++],ch); return ind; } int Prim() { int res=0; int i,j,k; for(i=1;i<nv-1;i++) { mstEdge[i].sv = 1; mstEdge[i].ev = i+1; mstEdge[i].w = gam[1][i+1]; } for(k=2;k<nv;k++) { int minw = mstEdge[k-1].w,ind = k-1; for(i=k;i<nv-1;i++) if(minw > mstEdge[i].w) { minw = mstEdge[i].w; ind = i; } res += minw; Edge tmp = mstEdge[ind]; mstEdge[ind] = mstEdge[k-1]; mstEdge[k-1]=tmp; j = mstEdge[k-1].ev; for(i=k;i<nv-1;i++) { int v = mstEdge[i].ev,w = gam[j][v]; if(mstEdge[i].w > w) { mstEdge[i].w = w; mstEdge[i].sv = j; } } } return res; } void MaxWeightEdgeInCycle(int mv,int sv,int ev,int& maxw,int& ind) { if(mv == ev) { isCycle = true; return; } for(int i=0;i<nv-1;i++) { if(mstEdge[i].sv != ev && mstEdge[i].ev != ev) continue; if(mstEdge[i].sv == ev && mstEdge[i].ev != sv) { MaxWeightEdgeInCycle(mv,ev,mstEdge[i].ev,maxw,ind); if(isCycle) { if(maxw<mstEdge[i].w && mstEdge[i].ev!=0) { maxw=mstEdge[i].w; ind=i; } break; } } else if(mstEdge[i].sv != sv && mstEdge[i].ev == ev) { MaxWeightEdgeInCycle(mv,ev,mstEdge[i].sv,maxw,ind); if(isCycle) { if(maxw<mstEdge[i].w && mstEdge[i].sv!=0) { maxw=mstEdge[i].w; ind=i; } break; } } } } void Solve() { int i; bool exist[MAX_NV]; ans = Prim(); int minw = INF+1,ev = -1; for(i=1;i<nv;i++) { if(gam[0][i] < minw) { minw = gam[0][i]; ev = i; } exist[i]=false; } ans += minw; exist[ev]=true; mstEdge[0].w=minw; mstEdge[0].sv=0; mstEdge[0].ev=ev; for(int d=2;d<=s;d++) { int dec = INF+1,edgeInd=-1; ev = -1; for(i=1;i<nv;i++) { if(exist[i]==true) continue; int maxw=0,ind=-1; isCycle = false; MaxWeightEdgeInCycle(0,0,i,maxw,ind); if(dec > gam[0][i]-maxw) { dec=gam[0][i]-maxw; edgeInd=ind; ev=i; } } if(dec>=0) break; else { mstEdge[edgeInd].sv=0; mstEdge[edgeInd].ev=ev; mstEdge[edgeInd].w=gam[0][ev]; ans += dec; exist[ev]=true; } } } int main() { int i; char name1[12],name2[12]; int ne; strcpy(name[0],"Park"); memset(gam,0x7f,sizeof(gam)); while(scanf("%d",&ne)!=EOF) { nv = 1; int dis,ind1,ind2; for(i=0;i<ne;i++) { cin >> name1 >> name2 >> dis; ind1=IndName(name1); ind2=IndName(name2); gam[ind1][ind2] = gam[ind2][ind1] = dis; } cin >> s; Solve(); printf("Total miles driven: %d\n",ans); } return 0; }