为什么我的代码中会有额外的输出?

时间:2014-09-15 18:11:08

标签: c++

我正在解决this question on CodeChef

这是我的解决方案

#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;
}

我正在为测试用例获得正确的输出,但它最后打印了一个额外的单词,我无法弄清楚为什么。 这是我得到的输入和输出

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$  

,而正确的输出是

Madrid Paris 100$  
Paris Munich 200$  
Munich Warsaw 150$  
Warsaw Kiev 120$    
570$  

我猜这是与IO机制相关的东西,但不知道如何解决这个问题

1 个答案:

答案 0 :(得分:0)

没有你的问题与IO机制无关,而是在逻辑上中断。你的循环

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];
}

对于mrev [current] ==“kiev”打印该值,因为[current]等于0并且你有mrev [0]和weight [0]的空字符串。您可能希望将循环中的条件更改为:

while( to[current] != 0 )

解决此问题。

相关问题