Sweet butter (shortest path)

Insert picture description here

Idea: The shortest path violence, put the sugar in each position and then run the shortest path to see the distance from the current position to several positions with cows. Remember to multiply the number of cows and take the minimum

//#pragma GCC optimize(2)
#include<bits/stdc++.h>
 
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=1e9+7;
const int N=1e5+5;
const int inf=0x7f7f7f7f;

int gcd(int a,int b)
{
    
    
    return b==0?a:gcd(b,a%b);
}
 
ll lcm(ll a,ll b)
{
    
    
    return a*(b/gcd(a,b));
}
 
template <class T>
void read(T &x)
{
    
    
    char c;
    bool op = 0;
    while(c = getchar(), c < '0' || c > '9')
        if(c == '-')
            op = 1;
    x = c - '0';
    while(c = getchar(), c >= '0' && c <= '9')
        x = x * 10 + c - '0';
    if(op)
        x = -x;
}
template <class T>
void write(T x)
{
    
    
    if(x < 0)
        x = -x, putchar('-');
    if(x >= 10)
         write(x / 10);
    putchar('0' + x % 10);
}
ll qsm(int a,int b,int p)
{
    
    
    ll res=1%p;
    while(b)
    {
    
    
        if(b&1)
            res=res*a%p;
        a=1ll*a*a%p;
        b>>=1;
    }
    return res;
}
struct node
{
    
    
    int to,nex,w;
}edge[N];
int tot=0,head[N];
int dis[N];
int vis[N];
int n,m,k;
int a[N];
void add(int u,int v,int w)
{
    
    
    tot++;
    edge[tot].nex=head[u];
    edge[tot].to=v;
    edge[tot].w=w;
    head[u]=tot;
}
int dj(int ts)
{
    
    
   
    memset(dis,inf,sizeof dis);
    memset(vis,0,sizeof vis);
    //cout<<ts<<' '<<te<<endl;
    priority_queue<PII,vector<PII>,greater<PII> > q;
    q.push({
    
    0,ts});
    dis[ts]=0;
    while(!q.empty())
    {
    
    
        auto now=q.top();
        q.pop();
        int d=now.first,u=now.second;
        if(vis[u])continue;
        vis[u]=1;
        for(int i=head[u];~i;i=edge[i].nex)
        {
    
    
            int v=edge[i].to;
            if(dis[v]>d+edge[i].w)
            {
    
    
                dis[v]=d+edge[i].w;
                q.push({
    
    dis[v],v});
            }
        }

    }
    int ans=0;
    for(int i=1;i<=m;i++) if(a[i]) ans+=dis[i]*a[i];
   // cout<<ans<<endl;
    return ans;

}
int main()
{
    
    

     memset(head,-1,sizeof head);
    
      scanf("%d%d%d",&n,&m,&k);
      for(int i=1;i<=n;i++)
      {
    
    
          int x;
          scanf("%d",&x);
          a[x]++;
      }
      for(int i=1;i<=k;i++)
      {
    
    
          int u,v,w;
          scanf("%d%d%d",&u,&v,&w);
            add(u,v,w);
            add(v,u,w);
          
      }
      int ans=inf;
      for(int i=1;i<=m;i++) ans=min(ans,dj(i));
      printf("%d",ans);
       
      

    return 0;

}


Guess you like

Origin blog.csdn.net/qq_43619680/article/details/109548525