香甜的黄油

来源:互联网 发布:摇钱树网吧计费软件 编辑:程序博客网 时间:2024/04/30 02:55
Problem Description农夫John发现做出全威斯康辛州最甜的黄油的方法:糖。把糖放在一片牧场上,他知道N(1<=N<=500)头奶牛会过来舔它,这样就能做出能卖好价钱的超甜黄油。当然,他将付出额外的费用在奶牛上。农夫John很聪明。像以前的巴普洛夫,他知道他可以训练这些奶牛,让它们在听到铃声时去一个特定的牧场。他打算将糖放在那里然后下午发出铃声,以至他可以在晚上挤奶。农夫John知道每头奶牛都在各自喜欢的牧场(一个牧场不一定只有一头牛)。给出各头牛在的牧场和牧场间的路线,找出使所有牛到达的路程和最短的牧场(他将把糖放在那)。Input输入有多组数据,每组数据第1行有三个数:奶牛数N,牧场数P(2<=P<=800),牧场间道路数C(1<=C<=1450)。第2行到第N+1行:1到N头奶牛所在的牧场号。第N+2行到第N+C+1行:每行有三个数:相连的牧场A、B,两牧场间距(1<=D<=255),当然,连接是双向的。Output对于每组数据输出一行,奶牛必须行走的最小的距离和。Sample Input3 4 52341 2 11 3 52 3 72 4 33 4 5Sample Output8//题解:简单SPFA算法。//标程:#include<iostream>#include<cstdio>#include<cstring>#include<vector>#include<queue>using namespace std;vector<int> v[810];queue<int> q;const int cs = 1 << 30;int minn, n, p, c;int dis[810], vis[810], map[810][810], a[810];void spfa(int k){    int i;    for(i = 1; i <= p; i ++)  dis[i] = cs;    dis[k] = 0;    memset(vis,0,sizeof(vis));    q.push(k);    while(!q.empty())    {        int temp = q.front();         for(i = 0; i < v[temp].size(); i ++)        {int z = v[temp][i];            if(map[temp][z] != cs && dis[z] > dis[temp] + map[temp][z])            {   dis[z] = dis[temp] + map[temp][z];if(!vis[z]){q.push(z);vis[z] = 1;}}        }vis[temp] = 0;q.pop();    }    int sum = 0;    for(i = 1; i <= n; i ++)         if(dis[a[i]] < cs) sum += dis[ a[i] ];    if(sum < minn) minn = sum;}int main(){//     freopen("a.txt","r",stdin);    int i, j;    while(cin >> n >> p >> c)    {        minn = cs;        for(i = 1; i <= n; i ++)            cin >> a[i];        for(i = 0; i <= p; i ++) v[i].clear();        int x, y, di;        for(i = 1; i <= p; i ++)            for(j = 1; j <= p; j ++)                map[i][j] = cs; //i与j不连通;        for(i = 1; i <= c; i ++)        {            cin >> x >> y >> di;            v[x].push_back(y);            v[y].push_back(x);            map[x][y] = map[y][x] = di;        }        for(i = 1; i <= p; i ++)        {            while(!q.empty()) q.pop();            spfa(i);        }        cout << minn << endl;    }    return 0;}

0 0
原创粉丝点击