现在地图上有N个城市(你所在的城市编号为1),但是你的汽车油箱容量只有V,你只能在到达每个城市时才能够补充满油箱。现在告诉你每两个城市之间所需要消耗的油量(两个城市之间的路可能不止一条,消耗的油量也可能不同),是否存在一种方案使你能够周游这N个城市(每个城市可以走多次)。
现在地图上有N个城市(你所在的城市编号为1),但是你的汽车油箱容量只有V,你只能在到达每个城市时才能够补充满油箱。现在告诉你每两个城市之间所需要消耗的油量(两个城市之间的路可能不止一条,消耗的油量也可能不同),是否存在一种方案使你能够周游这N个城市(每个城市可以走多次)。
多组样例到文件尾结束。
每组样例第一行输入N,M,V,表示城市数目,道路数,油箱容量。 2 <= N <= 10000, 1 <= M <= 50000, 1 <= V <= 1000。
接下来输入M行,每行包含Xi,Yi,Ci。表示城市Xi,Yi之间存在一条耗油量Ci的路。1<=X,Y<=N, 1<=Ci<=1000。
PS:道路是双向的。
如果存在输出YES
否则输出NO
4 4 2
1 4 2
1 3 2
2 3 1
3 4 4
3 3 2
1 2 3
1 3 2
2 3 3
YES
这题点太多了,所以需要用邻接表存储,而且要开到否则会RE。。。1WA,1RE,
#include <iostream>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 1000000 + 10;
const int INF = 99999999;
int head[maxn];
int num[maxn];
int d[maxn];
int visit[maxn];
int V,M,C;
int size;
struct Edge
{
int to,w,next;
} E[maxn];
void init()
{
memset(head,-1,sizeof(head));
fill(d,d+V+1,INF);
size = 0;
}
void addedge(int u,int v,int x)
{
E[size].to = v;
E[size].w = x;
E[size].next = head[u];
head[u] = size++;
}
int SPFA(int s)
{
queue<int> q;
fill(num,num+V+1,0);
fill(visit,visit+V+1,0);
d[s]=0;
q.push(s);
visit[s] = 1;
while(!q.empty())
{
int u = q.front();
q.pop();
for(int i=head[u]; i!=-1; i=E[i].next)
{
if(d[E[i].to] > d[u] + E[i].w && E[i].w <= C )
{
d[E[i].to] = d[u]+E[i].w;
q.push(E[i].to);
}
}
}
return 1;
}
int main()
{
#ifdef xxz
freopen("in.txt","r",stdin);
#endif // xxz
while(cin>>V>>M>>C)
{
init();
for(int i = 0; i < M; i++)
{
int a,b,c;
cin>>a>>b>>c;
addedge(a,b,c);
addedge(b,a,c);
}
SPFA(1);
bool flag = true;
for(int i = 1; i <= V; i++)
{
if(d[i] >= INF)
{
flag = false;
break;
}
}
if(!flag)cout<<"NO"<<endl;
else cout<<"YES"<<endl;
}
return 0;
}原文:http://blog.csdn.net/u013445530/article/details/44627559