P1828 [USACO3.2]香甜的黄油 Sweet Butter【SPFA算法】

题目描述

农夫John发现做出全威斯康辛州最甜的黄油的方法:糖。把糖放在一片牧场上,他知道N(1<=N<=500)只奶牛会过来舔它,这样就能做出能卖好价钱的超甜黄油。当然,他将付出额外的费用在奶牛上。

农夫John很狡猾。像以前的Pavlov,他知道他可以训练这些奶牛,让它们在听到铃声时去一个特定的牧场。他打算将糖放在那里然后下午发出铃声,以至他可以在晚上挤奶。

农夫John知道每只奶牛都在各自喜欢的牧场(一个牧场不一定只有一头牛)。给出各头牛在的牧场和牧场间的路线,找出使所有牛到达的路程和最短的牧场(他将把糖放在那)

输入格式

第一行: 三个数:奶牛数N,牧场数(2<=P<=800),牧场间道路数C(1<=C<=1450)

第二行到第N+1行: 1到N头奶牛所在的牧场号

第N+2行到第N+C+1行: 每行有三个数:相连的牧场A、B,两牧场间距离D(1<=D<=255),当然,连接是双向的

输出格式

一行 输出奶牛必须行走的最小的距离和

输入输出样例

输入 #1

3 4 5
2
3
4
1 2 1
1 3 5
2 3 7
2 4 3
3 4 5

输出 #1

8

自己没想到的点:最优牧场不一定在牧牛所在的牧场,也可能是没有牧牛的牧场!!!!!

AC代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<queue>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ull;
const int N=10000;
struct node{
	int to;
	int data;
};
vector<node>mp[N];
ull low[N];
int ind[N];
int n,p,c;
ull spfa(int s){
	memset(low,INF,sizeof(low));
	int start,next;
	queue<int>Q;
	start=s;
	Q.push(start);
	low[s]=0;
	while(!Q.empty()){
		//cout<<start<<endl;
		start=Q.front();
		Q.pop();
		for(int i=0;i<mp[start].size();i++){
			next=mp[start][i].to;
			//cout<<mp[start][i].data<<"---"<<endl;
			if(low[next]>low[start]+mp[start][i].data){
				low[next]=low[start]+mp[start][i].data;	
				//cout<<next<<" "<<low[next]<<"--"<<endl;
				Q.push(next);
			}
		}
	}
	ull sum=0;
	for(int j=1;j<=n;j++){
		sum+=low[ind[j]];
		//cout<<index[i]<<' '<<low[index[i]]<<endl;
	}
	return sum;
}
int main(){
	scanf("%d%d%d",&n,&p,&c);
	for(int i=1;i<=n;i++){
		scanf("%d",&ind[i]);
	}
	for(int i=1;i<=c;i++){
		int u,v,w;
		scanf("%d%d%d",&u,&v,&w);
		node temp;
		temp.to=v;temp.data=w;mp[u].push_back(temp);
		temp.to=u;mp[v].push_back(temp);
	}
	ull minn=INF;
	for(int i=1;i<=p;i++){
		//cout<<low[1]<<endl;
		ull sum=spfa(i);
		if(minn>sum){
			 minn=sum;
		}
	}
	printf("%lld\n",minn);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

瘾ิۣۖิۣۖิۣۖิꦿ

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

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

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

打赏作者

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

抵扣说明:

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

余额充值