【SSL】1693 & 【洛谷】P1828 香甜的黄油
Time Limit:1000MS
Memory Limit:65536K
Description
农夫John发现做出全威斯康辛州最甜的黄油的方法:糖。把糖放在一片牧场上,他知道N(1<=N<=500)只奶牛会过来舔它,这样就能做出能卖好价钱的超甜黄油。当然,他将付出额外的费用在奶牛上。
农夫John很狡猾。像以前的Pavlov,他知道他可以训练这些奶牛,让它们在听到铃声时去一个特定的牧场。他打算将糖放在那里然后下午发出铃声,以至他可以在晚上挤奶。
农夫John知道每只奶牛都在各自喜欢的牧场(一个牧场不一定只有一头牛)。给出各头牛在的牧场和牧场间的路线,找出使所有牛到达的路程和最短的牧场(他将把糖放在那)
Input
第一行: 三个数:奶牛数N,牧场数(2<=P<=800),牧场间道路数C(1<=C<=1450)
第二行到第N+1行: 1到N头奶牛所在的牧场号
第N+2行到第N+C+1行: 每行有三个数:相连的牧场A、B,两牧场间距离D(1<=D<=255),当然,连接是双向的
Output
一行 输出奶牛必须行走的最小的距离和
Sample Input
3 4 5
2
3
4
1 2 1
1 3 5
2 3 7
2 4 3
3 4 5
样例图形
P2
P1 @--1--@ C1
\ |\
\ | \
5 7 3
\ | \
\| \ C3
C2 @--5--@
P3 P4
Sample Output
8
{说明:放在4号牧场最优 }
思路
做p次单源最短路,也就是多源最短路。
计算距离和。
找最小值。
代码
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<cmath>
#include<queue>
#include<cstring>
using namespace std;
struct jgt
{
int w,s;
};
struct NOTE
{
int x,y,s,nxt;
}f[4000010];
bool operator < (const jgt &a,const jgt &b)
{
return a.s>b.s;
}
priority_queue<jgt>q;
int n,p,c,dx,dy,tot=0;
int head[2010],cow[2010];
int dis[2010][2010];
bool d[2010];
void input()
{
int i,j,x,y,z;
scanf("%d%d%d",&n,&p,&c);
for(i=1;i<=n;i++)
scanf("%d",&cow[i]);
for(i=1;i<=c;i++)
{
scanf("%d%d%d",&x,&y,&z);
tot++;//建边
f[tot].x=x;
f[tot].y=y;
f[tot].s=z;
f[tot].nxt=head[x];
head[x]=tot;
tot++;
f[tot].x=y;
f[tot].y=x;
f[tot].s=z;
f[tot].nxt=head[y];
head[y]=tot;
}
return;
}
void DIJ(int x)
{
jgt tem,temp;
int i,j,mn,w,v;
memset(d,0,sizeof(d));
for(i=0;i<=p;i++)
dis[x][i]=dis[i][x]=100000000;
for(i=head[x];i>0;i=f[i].nxt)
{
dis[x][f[i].y]=dis[f[i].y][x]=f[i].s;
tem.w=f[i].y;
tem.s=f[i].s;
q.push(tem);
}
for(dis[x][x]=0,d[x]=1;!q.empty();)//用小顶堆
{
tem=q.top();
q.pop();
d[tem.w]=1;
for(j=head[tem.w];j>0;j=f[j].nxt)//松弛
{
if(!d[f[j].y]&&tem.s+f[j].s<dis[x][f[j].y])
{
dis[x][f[j].y]=dis[f[j].y][x]=tem.s+f[j].s;
temp.w=f[j].y;
temp.s=dis[f[j].y][x];
q.push(temp);
}
}
}
return;
}
int main()
{
int i,j,sum,ans=100000000;
input();
for(i=1;i<=p;i++)
{
DIJ(i);
for(sum=0,j=1;j<=n;j++)//计算距离和
sum+=dis[i][cow[j]];
ans=min(ans,sum);
}
printf("%d",ans);
return 0;
}