7-11 特殊最小成本修路 (10分)(HBU寒假训练营)

n个城镇之间目前有一些道路连接,但道路都是年久失修的土道。现在政府准备将其中一些土道改造为标准公路,希望标准公路能够将所有城镇连通且总成本最小,但其中有一个城镇比较特殊,受地形等限制,最多只能有两条标准公路通过该镇。请编写程序,找出一种满足上述条件的、总成本最小的改造方案,若不存在改造方案,则亦能识别。假定道路是双向的。

输入格式:

输入包含多组数据。每组数据第一行是3个整数n、v和e,均不超过50,n为城镇数目,城镇编号0至n-1。v为最能有两条标准公路的城镇编号,e为现有的土路条数,接下来是e行表示每条道路信息,每行为3个非负整数a、b、c,表示城镇a和城镇b间现有一条道路,若将其改造为标准公路,成本为c。

输出格式:

对每组数据输出一行,为一个整数,表示满足要求的最小成本,若不存在改造方案,则输出-1。

输入样例:

5 0 8
0 1 1
0 2 1
0 3 1
0 4 1
1 4 100
1 2 100
2 3 100
3 4 100
5 0 4
0 1 1
0 2 1
0 3 1
0 4 1

输出样例:

202
-1

代码:主要采用克鲁斯卡尔算法,寻找最小生成树

#include<bits/stdc++.h>
using namespace std;
typedef struct enode
{
    int a;
    int b;
    int cost;
}Enode;
int father[55];
bool cmp(Enode a, Enode b)
{
    if(a.cost<b.cost){
        return true;
    }else{
        return false;
    }
}
int find(int x)
{
    int a = x ;
    while(x!=father[x]){
        x=father[x];
    }
    while(a!=father[a])
    {
        int z=a;
        a=father[a];
        father[z]=x;
    }
    return x;
}
int main()
{
    int n,v,e;
    while(cin>>n>>v>>e)
    {
        Enode s[e];
        int i;
        for(i=0;i<e;i++){
            cin>>s[i].a>>s[i].b>>s[i].cost;
        }
        sort(s,s+e,cmp);
        for(i=0;i<55;i++){
            father[i]=i;
        }
        int count=0;
        int num=0;
        int sum=0;
        for(i=0;i<e;i++){
            if(s[i].a==v||s[i].b==v){
                int fa=find(s[i].a);
                int fb=find(s[i].b);
                if(count<2 && fa!=fb){
                    count++;
                    num++;
                    sum+=s[i].cost;
                    father[fa]=fb;
                }
            }else if(s[i].a!=v && s[i].b!=v){
                int fa=find(s[i].a);
                int fb=find(s[i].b);
                if(fa!=fb){
                    num++;
                    sum+=s[i].cost;
                    father[fa]=fb;
                }
            }
            if(num == n-1){
                break;
            }  
        }
        if(num==n-1){
            cout<<sum<<endl;
        }else{
            cout<<-1<<endl;
        }
    }
    return 0;
}

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
SVM算法通过将数据映射到高维空间,将数据分为两个类别。SVM算法的目标是找到一个超平面,可以将数据分为两个类别。SMO算法是一种优化算法,用于求解SVM中的二次规划问题。下面介绍如何使用SMO算法编写SVM对CIFAR-10数据进行分类。 首先,我们需要加载CIFAR-10数据集。CIFAR-10数据集包含10个类别的60000个32x32彩色图像。每个类别包含6000个图像。我们将使用Python中的pickle模块来加载数据集。以下是加载数据集的代码: ```python import pickle import numpy as np def unpickle(file): with open(file, 'rb') as fo: dict = pickle.load(fo, encoding='bytes') return dict def load_cifar10_data(): xs = [] ys = [] for j in range(5): d = unpickle('cifar-10-batches-py/data_batch_%d' % (j + 1)) x = d[b'data'] y = d[b'labels'] xs.append(x) ys.append(y) d = unpickle('cifar-10-batches-py/test_batch') xs.append(d[b'data']) ys.append(d[b'labels']) x = np.concatenate(xs) / np.float32(255) y = np.concatenate(ys) return x.reshape((len(x), -1)), np.array(y) ``` 接下来,我们将使用SMO算法来训练SVM模型。以下是使用SMO算法训练SVM模型的代码: ```python class SVM: def __init__(self, C, toler, kernel_opt=('linear', 0)): self.C = C self.toler = toler self.kernel_opt = kernel_opt def fit(self, X, y): n_samples, n_features = X.shape alpha = np.zeros(n_samples) b = 0 kernel = kernel_set[self.kernel_opt[0]] K = np.zeros((n_samples, n_samples)) for i in range(n_samples): K[:, i] = kernel(X, X[i], self.kernel_opt[1]) iter = 0 while iter < max_iter: num_changed_alphas = 0 for i in range(n_samples): Ei = np.dot(alpha * y, K[:, i]) + b - y[i] if (y[i] * Ei < -self.toler and alpha[i] < self.C) or \ (y[i] * Ei > self.toler and alpha[i] > 0): j = np.random.choice([x for x in range(n_samples) if x != i]) Ej = np.dot(alpha * y, K[:, j]) + b - y[j] alpha_i_old, alpha_j_old = alpha[i], alpha[j] if y[i] != y[j]: L = max(0, alpha[j] - alpha[i]) H = min(self.C, self.C + alpha[j] - alpha[i]) else: L = max(0, alpha[i] + alpha[j] - self.C) H = min(self.C, alpha[i] + alpha[j]) if L == H: continue eta = 2.0 * K[i, j] - K[i, i] - K[j, j] if eta >= 0: continue alpha[j] -= y[j] * (Ei - Ej) / eta alpha[j] = min(alpha[j], H) alpha[j] = max(alpha[j], L) if abs(alpha[j] - alpha_j_old) < 1e-5: continue alpha[i] += y[i] * y[j] * (alpha_j_old - alpha[j]) b1 = b - Ei - y[i] * (alpha[i] - alpha_i_old) * K[i, i] - \ y[j] * (alpha[j] - alpha_j_old) * K[i, j] b2 = b - Ej - y[i] * (alpha[i] - alpha_i_old) * K[i, j] - \ y[j] * (alpha[j] - alpha_j_old) * K[j, j] if 0 < alpha[i] < self.C: b = b1 elif 0 < alpha[j] < self.C: b = b2 else: b = (b1 + b2) / 2 num_changed_alphas += 1 if num_changed_alphas == 0: iter += 1 else: iter = 0 self.X = X self.y = y self.kernel = kernel self.alpha = alpha self.b = b def predict(self, X): n_samples, n_features = X.shape K = np.zeros((n_samples, len(self.X))) for i in range(n_samples): K[i, :] = self.kernel(self.X, X[i], self.kernel_opt[1]) y_pred = np.dot(self.alpha * self.y, K) + self.b return np.sign(y_pred) ``` 最后,我们使用以下代码来加载数据集并使用SMO算法训练SVM模型: ```python X, y = load_cifar10_data() y[y == 0] = -1 X_train, X_test = X[:50000], X[50000:] y_train, y_test = y[:50000], y[50000:] svm = SVM(C=1.0, toler=0.001, kernel_opt=('rbf', 1)) svm.fit(X_train, y_train) y_pred_train = svm.predict(X_train) y_pred_test = svm.predict(X_test) train_acc = np.mean(y_train == y_pred_train) test_acc = np.mean(y_test == y_pred_test) print('train_acc:', train_acc) print('test_acc:', test_acc) ``` 这样我们就使用SMO算法编写了SVM对CIFAR-10数据进行分类的代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rain Sure

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值