C - Plucking fruits
Time Limit:3000MS MemoryLimit:0KB 64bit IO Format:%lld &%llu
Description
xxx lives in aforest , and everyday he jumps from one tree to another to pick fruits to eat.If the distance that he jumps is too short, the very weak xxx will fall off.Suppose that the paths in the forest are known and the initial position, theterminal position and the minimum distance that xxx can jump are known too.Please answer whether he can get the fruits this time?
Input
There aremultiple test cases. For each test case, the data in the first line are 3positive integers: n , m , and r . n meansthe number of trees in xxx's territory, trees are numbered from 1 to n . m meansthe number of pairs of trees that can be reached from each other. rmeansthe number of times that xxx picks the fruits. Each of the following m lineshas 3 integers a , b and c . a and b aretree numbers andc is the distance between tree a andtree b . Each of the last r lines has threenumbers, indicating the initial tree number, terminal tree number and theminimum distance that xxx can jump this time. Proceed to the end of the inputfile
(1 <= n<=1000, 1 < a, b<=n, 0 < c<=100000,1 <=m, r<=n* n)
Output
For each testcase, output ``yes" or ``no" in one line for each jump journeyxxx makes. ``yes" means xxxcan jump from initial position to the terminal position to get the fruits, ``no" means xxx cannot. Please output theresult as in the Sample Output.
Sample Input
2 1 1
1 2 1
2 1 1
Sample Output
Case 1:
yes
题目大意
给了n棵树,和m条路径,给出两棵树之间的每次跳动的最短距离,判断是否可以到达。
题目分析
将询问路线和普通路线一同计算,然后直接利用构造最大树的方法进行计算,遇到询问路线,就判断两点是否连通即可。
AC代码
#include <iostream>
#include <cstdlib>
using namespace std;
struct Line
{
int u,v;
int dis;
int num;
bool ans;
}a[1001*1001*2];
int n,m,r,len;
int fa[1001];
int cmp1(const void *a, const void *b)
{
Line *c=(Line *)a;
Line *d=(Line *)b;
return d->dis - c->dis;
}
int cmp2(const void *a, const void *b)
{
Line *c=(Line *)a;
Line *d=(Line *)b;
return c->num - d->num;
}
int ff(int u)
{
if(fa[u]==u)return u;
fa[u]=ff(fa[u]);
return fa[u];
}
void init()
{
int i;
int u,v,c;
for (i=0;i<=n;i++)
fa[i]=i;
for (i=1,len=1;i<=m;i++,len++)
{
cin>>u>>v>>c;
a[len].u=u;
a[len].v=v;
a[len].dis=c;
a[len].num=10000000;
}
for (i=1;i<=r;i++,len++)
{
cin>>u>>v>>c;
a[len].u=u;
a[len].v=v;
a[len].dis=c;
a[len].num=i;
a[len].ans=1;
}
}
void work()
{
int i,len=m+r,k;
for (i=1,k=1;i<=len && k<n;i++)
{
int fu=ff(a[i].u),fv=ff(a[i].v);
if(a[i].num==10000000)
{
if(fu!=fv)
{
fa[fu]=fv;
k++;
}
}
else
if(fu!=fv)
a[i].ans=0;
}
}
void out()
{
int i;
for (i=1;i<=r;i++)
{
if(a[i].ans)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
}
int main()
{
int T=1;
while (cin>>n>>m>>r)
{
cout<<"Case "<<T++<<":"<<endl;
init();
qsort(a+1,m+r,sizeof(a[0]),cmp1);
work();
qsort(a+1,m+r,sizeof(a[0]),cmp2);
out();
}
return 0;
}