1

I am trying to solve the following problem from ACM Timus: http://acm.timus.ru/problem.aspx?space=1&num=1242 , but I don't how to read the input correctly. I am using two while loops. The first one terminates once a string is written in the input but the second one doesn't work after that. Here's my code:

#include <iostream>
#include <vector>
using namespace std;



struct Pair
{  
    void AddParent(int a)
    { parents.push_back(a); }
    void AddChild(int a)
    { children.push_back(a);}
    vector<int> parents;
    vector<int> children;
};

vector<bool> visited;
vector<Pair> graph;

void DFS1(int n)
{
    visited[n] = true;
    for(int i = 0 ; i < graph[n].parents.size() ; i++)
    {
        int t = graph[n].parents[i];
        if(!visited[t])
            DFS1(t);
    }
    return;
}

void DFS2(int n)
{
    visited[n] = true;
    for(int i = 0 ; i < graph[n].children.size() ; i++)
    {
        int t = graph[n].children[i];
        if(!visited[t])
            DFS2(t);
    }
    return;
}


int main()
{
    int n;
    cin >> n; 
    graph.resize(n);
    visited.resize(n);
    int a,b,c;
    vector<int> victim;

////////////////////////////////
    while(cin >> a && cin >> b)
    {   a--;b--;
        graph[a].AddParent(b);
        graph[b].AddChild(a);
    }

    cin.clear();
    cin.ignore();

    while(cin >> c)
    {
        victim.push_back(c);
    }

////////////////////////////////    

    for(int i = 0 ; i < victim.size() ; i++)
        if(!visited[victim[i]]){
            DFS1(victim[i]);
            DFS2(victim[i]);
        }


    bool vis = false;
    for(int i = 0 ;  i < n ; i++)
        if(!visited[i])
        { 
            vis = true;
            cout << i + 1 << " ";
        }
        if(!vis)
            cout << 0;

return 0;
}
Narek Margaryan
  • 334
  • 1
  • 4
  • 11

1 Answers1

2

Before going to the second while loop you should clear the input stream cin.

    while(cin >> a && cin >> b)
    {   a--;b--;
        graph[a].AddParent(b);
        graph[b].AddChild(a);
    }
    cin.clear();
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    while(cin >> c)
    {
        victim.push_back(c);
    }

And include the header limits

Why would we call cin.clear() and cin.ignore() after reading input?

Community
  • 1
  • 1
sajas
  • 1,599
  • 1
  • 17
  • 39
  • You wrote my words! :) – Mike Jan 14 '14 at 09:59
  • @user1978522 The function ignore takes the number of characters to be ignored as the first argument. By default it is set as 1. So if the string you entered has more than 1 character the function fails. I have changed the code to take max limit. – sajas Jan 14 '14 at 10:24