The Child and Toy

Sample Input

Input
4 3
10 20 30 40
1 4
1 2
2 3
Output
40
Input
4 4
100 100 100 100
1 2
2 3
2 4
3 4
Output
400
Input
7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4
Output
160

题意:n个零件,m个连接方式,给出每一个零件的重量,拆一个零件需要消耗与它相连接的重量之和,问拆掉这个玩具最少消耗多少。

 

方法一:按照重量排序,先拆质量大的。

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <sstream>
#include <cstdio>
#include <vector>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#define MAX 0x3f3f3f3f
using namespace std;
typedef long long ll;
const double PI = acos(-1);
const int M=1e3+10;
#define inf 0x3f3f3f
vector <int> v[M];
struct A
{
    int p;
    int w;
}a[M];
int mapp[M][M];
int cmp(A x,A y)
{
    if(x.w==y.w)
        return x.p<y.p;
    return x.w>y.w;
}
int main()
{
    int n,m,aa,bb,ans=0,i,j,h;
    cin>>n>>m;
    for(i=1;i<=n;i++)
    {
        cin>>h;
        a[i].w=h;
        a[i].p=i;
    }
    for(i=0;i<m;i++)
    {
        cin>>aa>>bb;
        if(aa<bb)
            swap(aa,bb);
        mapp[aa][bb]=1;
        mapp[bb][aa]=1;
    }
    sort(a+1,a+n+1,cmp);
    int pp=0;
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=n;j++)
        {
            if(mapp[a[i].p][j]==1)
            {
                for(int k=1;k<=n;k++)//找到j位置现在在a数组中的位置
                {
                    if(a[k].p==j)
                        pp=k;
                }
                ans+=a[pp].w;
                mapp[a[i].p][j]=0;
                mapp[j][a[i].p]=0;
            }
        }
    }
    cout<<ans<<endl;
    return 0;
}

 

方法二:最小总代价,那么每次拆必须先拆能量值大的部件,这样才能保证总代价最小,因此每次读入绳子将两个部件相连时候,只要选择能量值较小的,就是结果。

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <sstream>
#include <cstdio>
#include <vector>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#define MAX 0x3f3f3f3f
using namespace std;
typedef long long ll;
const double PI = acos(-1);
const int M=1e3+10;
#define inf 0x3f3f3f
vector <int> v[M];
int main()
{
    int n,m,aa,bb,ans=0,i,j,h;
    int a[M];
    cin>>n>>m;
    for(i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    for(i=0;i<m;i++)
    {
        cin>>aa>>bb;
        ans+=min(a[aa],a[bb]);
    }
    cout<<ans<<endl;
    return 0;
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值