为什么我在代码中得到额外的输出
Why do I get extra output in my code?
我正在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 )
以解决此问题。
相关文章:
- 为什么我的代码在输出中增加了93天
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 在我的代码中,获得最大的Pair Wise产品C++和输出并不总是正确的
- 我无法获取以下代码的输出
- 为什么我的C++程序的程序集输出充满了 .ascii,没有汇编代码?
- 编译并运行后,输出未出现在 Visual Studio 代码中
- VI工作室代码错误无法打开输出文件主.exe
- 代码编译没有任何输出,入门程序
- 与其他编译器相比,相同的代码在工作室Microsoft提供不同的输出
- 可能我知道为什么这段代码没有给出任何输出吗?
- 从排序数组中删除重复项,具有不同代码方式的相同解决方案具有不同的输出
- Clang 给了我符号更改的警告,但代码仍然产生正确的输出
- 为什么这两个版本的代码给出不同的输出
- 以下与指针相关的代码的输出是什么?
- C++和 Python 中的代码相同,但输出不同
- 为什么我的代码块上没有显示输出?
- C++ 高级代码未给出正确的输出
- (C++)分解这个简单的输入/输出代码:
- 错误的输出代码
- 奇怪的输出(代码块codebblocks -16.01mingw-setup.exe)