首页 > 代码库 > 斯坦纳树

斯坦纳树

#line 5 "FoxTheLinguist.cpp"
#include <bits/stdc++.h>
using namespace std;

int head,tail,n,dl[10001],indl[10001],nxt[10001],len[10001],dis[3501][110],nd[10001],des[10001],cnt;
char st[1000001];

void spfa(int dis[]){
  head=1;tail=0;
  for (int i=0;i<=n*10;i++) dl[++tail]=i,indl[i]=1;
  while (head<=tail){
      for (int p=nd[dl[head]];p!=-1;p=nxt[p])
        if (dis[des[p]]>dis[dl[head]]+len[p]){
          dis[des[p]]=dis[dl[head]]+len[p];
          if (!indl[des[p]]){
            dl[++tail]=des[p];
          indl[des[p]]=1;
        }
      }
    indl[dl[head++]]=0;
  }
}

void Steiner(){
  for (int i=0;i<=n*10;i++) for (int j=0;j<=(1<<(n+1))-1;j++) dis[j][i]=1e9;
  dis[1][0]=0;
  for (int i=1;i<=n;i++) dis[1<<i][i*10]=0;
  for (int mask=1;mask<=(1<<(n+1))-1;mask++){
    for (int j=0;j<=10*n;j++)
      for (int k=(mask-1)&mask;k;k=(k-1)&mask)
        dis[mask][j]=min(dis[mask][j],dis[k][j]+dis[mask-k][j]);
    
    spfa(dis[mask]);
  }
}

void addedge(int x,int y,int le){
  nxt[++cnt]=nd[x];des[cnt]=y;len[cnt]=le;nd[x]=cnt;
}

class FoxTheLinguist {
    public:
    int minimalHours(int N, vector <string> I) {
      n=N;             
      for (int i=0;i<=10*n;i++) nd[i]=-1;
      for (int i=1;i<=n;i++) addedge((i-1)*10+1,0,0);
      for (int i=1;i<=n;i++)
        for (int j=10;j>2;j--)     
          addedge((i-1)*10+j-1,(i-1)*10+j,0);    
      cnt=-1;
      for (int i=0;i<I.size();i++)
        for (int j=0;j<I[i].size();j++)
          st[++cnt]=I[i][j];
                                                
      int po=0;                        
      while (st[po]>=A&&st[po]<=Z){
          int poa=(st[po]-A)*10+st[po+1]-0+1,pob=(st[po+4]-A)*10+st[po+5]-0+1,num=(st[po+7]-0)*1000+(st[po+8]-0)*100+(st[po+9]-0)*10+(st[po+10]-0);
          addedge(pob,poa,num);
          po+=12;
      }
      
      Steiner();
      
      if (dis[(1<<(n+1))-1][0]==1e9) return(-1);else return(dis[(1<<(n+1))-1][0]);
    } 
    

 

斯坦纳树