Welcome Guest.

2Answers

Why is my collection algorithm incorrect? The output is not correct. Or is there a problem with the idea?

Asked by: Ann Phillips 215 views IT February 1, 2019

Questions:

Description 

Today is Ignatius' birthday. He invites a lot of friends. Now it's dinner time. Ignatius wants to know how many tables he needs at least You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.

 

One important rule for this problem is that If I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.

 

For example : If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.

 

Input 

The input starts with an integer T(1<=T<=25) which indicates the number of test cases. Then T test cases follow. Each test case starts with two integers N and M(1<=N,M<=1000). N indicates the number of friends, the friends are marked from 1 to N. Then M lines follow. Each line Consists Of two integers A and B(A!=B), that means friend A and friend B know each other. There will be a blank line between two cases.

 

Output 

For each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.

 

Sample Input

 

5 3 

1 2 

2 3 

4 5

 

5 1 

2 5

 

Sample Output

 

4

#include"stdafx.h"

#include<iostream>

using namespace std;

int a[1040];

int b[1000];

int unionsearch( Int);

int main()

{

 

int n;

cin> >n;

while(n--)

{

int n1,n2,k;

int w=0;

for(int i=1;i<=n;i++)

{

a[i]=i;

}

cin>>n1>>n2;

k=n1;

while(n2--)

{

 

int t1,t2;

 

cin>>t1>>t2;

int root1,roo T2;

root1=unionsearch(t1);

root2=unionsearch(t2);

if(root1!=root2)

{

a[root1]=root2;

k--;

}

}

If(n)

cout<endlt;

b[w++]=k;

}

for(int i =0;i<n;i++)

{

cout<b[i]<<endl;

}

}

int unionsearch(int root)

{

int son,tmp;

son=root;

while(root!=a[root])

{

root=a[root];

}

while(son!=root)

{

tmp=a[son];

a[son]=root;

son=tmp;

}

return root;

}

2 Answers

  1. +3Votes  

    Regardless of whether your algorithm is correct, your program may not have output

    cin>>n;

    while(n–)

    . . .

    This is when n–=0 exits the loop. At this time, n is -1

    and your output loops

       for( Int i=0; i<n; i++)

    It is impossible to execute

    Cynthia- February 1, 2019 |

  2. +1Votes  

    Feeling should be a problem with code implementation, the algorithm should be correct, hope Adoption

    Matthew Harris- February 1, 2019 |