1214: Around the world
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 12 Solved: 2
[ Submit][ Status][ Web Board]
Description
现在地图上有N个城市(你所在的城市编号为1),但是你的汽车油箱容量只有V,你只能在到达每个城市时才能够补充满油箱。现在告诉你每两个城市之间所需要消耗的油量(两个城市之间的路可能不止一条,消耗的油量也可能不同),是否存在一种方案使你能够周游这N个城市(每个城市可以走多次)。
Input
多组样例到文件尾结束。
每组样例第一行输入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:道路是双向的。
Output
如果存在输出YES
否则输出NO
Sample Input
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
Sample Output
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;
}
还有一种方法可以用并查集解决:
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <queue>
#include <map>
#define INF 0x7fffffff
using namespace std;
const int MOD = 1e9 + 7;
const int N = 5e4 + 10;
int n, m, v;
struct edge {
int x, y, c;
} e[N];
int fa[N];
int cmp(edge a, edge b) {
return a.c < b.c;
}
int findx(int x) {
if(fa[x] == x) return x;
else return fa[x] = findx(fa[x]);
}
int main() {
while(scanf("%d%d%d", &n, &m, &v) != EOF) {
for(int i = 1; i <= n; i++) fa[i] = i;
for(int i = 0; i < m; i++) {
scanf("%d%d%d", &e[i].x, &e[i].y, &e[i].c);
}
sort(e, e + m, cmp);
int cnt = 0;
for(int i = 0; i < m && cnt < n - 1; i++) {
if(e[i].c > v) break;
int fx = findx(e[i].x);
int fy = findx(e[i].y);
if(fx != fy) {
fa[fx] = fy;
cnt++;
}
}
if(cnt == n - 1) puts("YES");
else puts("NO");
}
return 0;
}