为什么我在代码中得到额外的输出

Why do I get extra output in my code?

本文关键字:输出 代码 为什么      更新时间:2023-10-16

我正在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 %sn",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机制有关,但不知道如何修复这个

不,您的问题与IO机制无关,而是与逻辑中断有关。您的环路

while(current!=0)
{
    printf("%s %s %sn",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"打印该值,因为to[current]等于0,并且mrev[0]和weight[0]有空字符串。您可能希望将循环中的条件更改为:

while( to[current] != 0 )

以解决此问题。