您的位置:首页 > 其它

hdu 1535 Invitation Cards

2014-04-25 21:23 253 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1535

这道题两遍spfa,第一遍sfpa之后,重新建图,所有的边逆向建边,再一次spfa就可以了。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <algorithm>
#define maxn 1000001
using namespace std;
const int inf=1000000000;

long long dis1[maxn];
long long dis2[maxn];
int e1,head[maxn],e2;
bool vis[maxn];
int cnt[maxn];
int P,Q,s,e,n;
long long w;
struct node
{
int u,v,next;
long long w;
}p[maxn],p1[maxn];

void add(int u,int v,long long w)
{
p[e1].u=u;
p[e1].v=v;
p[e1].w=w;
p[e1].next=head[u];
head[u]=e1++;
}

bool spfa(int src,long long dis[])
{
queue<int>q;
memset(cnt,0,sizeof(cnt));
memset(vis,false,sizeof(vis));
for(int i=1; i<=n; i++) dis[i]=inf;
dis[src]=0;
vis[src]=true;
q.push(src);
while(!q.empty())
{
int u=q.front(); q.pop();
vis[u]=false;
for(int i=head[u]; i!=-1; i=p[i].next)
{
int vv=p[i].v;
long long ww=p[i].w;
if(dis[vv]>dis[u]+ww)
{
dis[vv]=dis[u]+ww;
if((++cnt[vv])>n) return false;
if(!vis[vv])
{
q.push(vv);
vis[vv]=true;
}
}
}
}
return true;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
e1=0;
memset(head,-1,sizeof(head));
scanf("%d%d",&P,&Q);
for(int i=0; i<Q; i++)
{
cin>>p1[i].u>>p1[i].v>>p1[i].w;
add(p1[i].u,p1[i].v,p1[i].w);
}
n=P;
spfa(1,dis1);
long long sum=0;
e1=0;
memset(head,-1,sizeof(head));
for(int i=0; i<Q; i++)
{
add(p1[i].v,p1[i].u,p1[i].w);
}
spfa(1,dis2);
for(int i=2; i<=n; i++)
{
sum+=(dis1[i]+dis2[i]);
}
cout<<sum<<endl;
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: