Luogu P1194 buy gifts (Prim)

Title description

It's the annual birthday of Mingming again, and obviously want to buy BB B-like things. Coincidentally, the price of this BB B-like thing is AA A yuan.

However, the store owner said that there have been recent promotions, namely:

If you bought the first II the I things, buy the first JJ J-like, then you can only spend KI, JK_ {the I, J} K the I , J yuan, even more coincidentally, KI, JK_ {the I, J} K the I , J actually equal KJ, IK_ {J,} the I K J , the I .

Now I want to know how much he will spend at least.

Input format

Two integers in the first line, A, BA, B A , B.

Next BB B lines, each line BB number. B, II the I line JJ J th of KI, {JK_ the I, J} K the I , J .

We们保Exchance KI, J = KJ, IK_ {I, J} = K_ {J, I} K I , J = K J , I 并且KI, I = 0K_ {I, I} = 0 K I , I = 0.

In particular, if KI, J = {0K_ the I, J} = 0 K the I , J = 0, then the toy without causing the between these two things.

Output format

An integer, the minimum amount of money to spend.

Sample input and output

Enter # 1
1 1
0

Output # 1
1
Enter # 2
3 3
0 2 4
2 0 2
4 2 0
Output # 2
7 
As long as you think of it, it's actually very simple. Two points with preferential relationship are used to build an edge. After the minimum spanning tree is added, add an a. See the data range and run Prim.
There are several important points:
1. Kij may be greater than a, so the edge should be min
. 2. To modify the Prim template slightly, ignore the case of Kij = 0 (no discount / i = j), because there is no discount When Kij = 0 instead of INF, it is not in line with general cognition 2333
#include <bits/stdc++.h>
using namespace std;
int a,b,mmap[1005][1005],d[1005],ans=0;
bool v[1005];
void prim()
{
    memset(d,0x3f,sizeof(d));
    memset(v,0,sizeof(v));
    d[1]=0;
    int i,j;
    for(i=1;i<b;i++)
    {
        int x=0;
        for(j=1;j<=b;j++)
        {
            if(!v[j] &&  (x==0 || (d[j] && d[j] < d[x]) ) ) x = j;
        }
        v[x]=1;
        int y;
        for(y=1;y<=b;y++)
        {
            if(mmap[x][y]==0)continue;
            if(!v[y])d[y]=min(d[y],mmap[x][y]);
        }
    }
}
int main()
{
    cin>>a>>b;
    int i,j;
    for(i=1;i<=b;i++)
    {
        for(j=1;j<=b;j++)
        {
            scanf("%d",&mmap[i][j]);
            mmap[i][j]=min(mmap[i][j],a);
        }
    }
    prim();
    for(i=2;i<=b;i++)
    {
        ans+=d[i];
    }
    cout<<ans+a;
    return 0;
}

 



Guess you like

Origin www.cnblogs.com/lipoicyclic/p/12735460.html