USACO3.2 Sweet Butter(butter)

最短路的题,看上去比较简单,但是坑爹的超时啊,泪奔了。。。floyd超时,priority_queue没搞好,最后模仿了一个SPFA算法,才算是过了。有时间好好研究下这几种最短路算法。

 

/*
ID:jzzlee1
PROB:butter
LANG:C++
*/
//#include<iostream>
#include<fstream>
#include<cstring>
#include<queue>
using namespace std;
ifstream cin("butter.in");
ofstream cout("butter.out");
const int MAX =1000000;
const int pp=801;
int n,p,c;
int cow[pp];
int graph[pp][pp];
int u[3000], v[3000],w[3000],nextt[3000],first[pp],d[pp];
int main()
{
	int i,j,k,e;
    for(i=0;i<pp;i++)
        for(j=0;j<pp;j++)
            graph[i][j]=MAX;
    for(i=0;i<pp;i++)
    {
		first[i]=-1;
		graph[i][i]=0;
	}
    cin>>n>>p>>c;
    int t1,t2,t3;
    for(i=0;i<n;i++)
        cin>>cow[i];
    for(e=0;e<2*c;e++)
    {
        cin>>t1>>t2>>t3;
        u[e]=t1;
		v[e]=t2;
		w[e]=t3;
        nextt[e]=first[u[e]];
        first[u[e]]=e;
        e++;
        u[e]=t2;
		v[e]=t1;
		w[e]=t3;
        nextt[e]=first[u[e]];
        first[u[e]]=e;
    }
    for(k=1;k<=p;k++)
    {
        queue<int> q;
        bool done[pp];
        memset(done,0,sizeof(done));
        for(i=0;i<=p;i++)
            d[i]=(i==k?0:MAX);
        q.push(k);
        while(!q.empty())
        {
            int x=q.front();q.pop();
            done[x]=0;
            for(e=first[x];e!=-1;e=nextt[e])
                if(d[v[e]]>d[x]+w[e])
                {
                    d[v[e]]=d[x]+w[e];
                    if(!done[v[e]])
                    {
                        done[v[e]]=true;
                        q.push(v[e]);
                    }
                }
        }
        for(i=1;i<=p;i++)
			graph[k][i]=d[i]<graph[k][i]?d

[i]:graph[k][i]; 
    }
    for(i=1;i<=p;i++)
		for(j=1;j<=p;j++)
			graph[j][i] = graph[i][j]  ;
    int mini = MAX;
    for(i=1;i<=p;i++)
    {
        int sum = 0;
        for(j=0;j<n;j++)
			sum+=graph[i][cow[j]];
        if(mini>sum)
			mini=sum;
    }
    cout<<mini<<endl;
 return 0;
}

你可能感兴趣的:(USACO)