I am solving this question on CodeChef
This is my solution
#include <cstdio>
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <cstdlib>
using namespace std;
char a[100];
char b[100];
char c[100];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
map <string,int> m;
map <int,string> mrev;
map <int,string> weight;
vector <int> incount(5000,0);
vector <int> to(5000,0);
int k,i;
for(i = 0,k = 1;i<n-1;i++)
{
scanf("%s",a);
string A(a);
scanf("%s",b);
string B(b);
scanf("%s",c);
string C(c);
int x,y;
if(m[A]==0)
{
m[A] = x = k++;
mrev[x] = A;
}
else
x = m[A];
if(m[B]==0)
{
m[B] = y = k++;
mrev[y] = B;
}
else
y = m[B];
to[x] = y;
weight[x] = C;
incount[y] = 1;
}
int N = k,current;
for(i=1;i<N;i++)
{
if(incount[i]==0)
{
current = i;
break;
}
}
int ans=0;
while(current!=0)
{
printf("%s %s %s\n",mrev[current].c_str(),mrev[to[current]].c_str(),weight[current].c_str());
string cost = weight[current].substr(0,weight[current].size()-1);
ans += atoi(cost.c_str());
current = to[current];
}
printf("%d$\n",ans);
}
return 0;
}
I'm getting the correct output for the test case but it prints an extra word in the end which I can't figure out why. This is the input and output I get
1
5
Warsaw Kiev 120$
Madrid Paris 100$
Munich Warsaw 150$
Paris Munich 200$
Madrid Paris 100$
Paris Munich 200$
Munich Warsaw 150$
Warsaw Kiev 120$
Kiev
570$
while the correct output is
Madrid Paris 100$
Paris Munich 200$
Munich Warsaw 150$
Warsaw Kiev 120$
570$
I'm guessing this is something related to the IO mechanism but don't know how to fix this