New beginning (minimum spanning tree, establishment of super source point)

Insert picture description here

Idea: If you remove the choice of a point to build a power station, then the answer is directly a minimum spanning tree. We need to choose a place to build a power station on the basis of the minimum spanning tree, then it can be regarded as starting from a super source point to each point The cost is the cost of building a power station, and then calculate the minimum spanning tree from the super source point

//#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;
}
int mp[2005][2005];
int dis[N];
int n,m,k;
int vis[N];
int prime()
{
    
    
    memset(dis,inf,sizeof dis);
    dis[0]=0;
    int res=0;
    for(int i=1;i<=n+1;i++)
    {
    
    
        int t=-1;
        for(int j=0;j<=n;j++)
        if(!vis[j]&&(t==-1||dis[t]>dis[j]))t=j;
        vis[t]=1;
        res+=dis[t];
        for(int j=0;j<=n;j++)dis[j]=min(dis[j],mp[t][j]);
    }
    return res;

}
int main()
{
    
    
    cin>>n;
    for(int i=1;i<=n;i++)
    {
    
    
        int x;
        cin>>x;
        mp[0][i]=x;
    }
    for(int i=1;i<=n;i++)
    {
    
    
        for(int j=1;j<=n;j++)
        {
    
    
            cin>>mp[i][j];
        }
    }
    cout<<prime()<<endl;
   
    

      
   return 0;

}


Guess you like

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