http://acm.zjut.edu.cn/ShowProblem.aspx?ShowID=1038
题目见上网址
我写的两个版本都WA,望高人指点
1,我用字符串处理,当平方和相等按序号排序
#include <stdio.h>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct p
{
int xh;
int he;
};
p x[5000];
string a[5000];
bool rule (p a,p b)
{
if (a.he==b.he)
return (a.xh<b.xh);
return (a.he<b.he);
}
int main (void)
{
int i,j,n;
while (scanf("%d",&n)==1)
{
if (n==0)
break;
for (i=0;i<n;++i)
{
cin>>a[i];
x[i].xh=i;
x[i].he=0;
for (j=0;j<a[i].size();j++)
{
if (a[i][j]=='-') continue;
x[i].he+=(a[i][j]-'0')*(a[i][j]-'0');
}
}
sort(&x[0],&x[n],rule);
for (i=0;i<n-1;++i)
{
cout<<a[(x[i].xh)]<<" ";
}
cout<<a[(x[n-1].xh)]<<endl;
}
return 0;
}
2我用int处理,当平方和相等按数字大小排序(我也试过按序号排序,还是不行。。)
#include <stdio.h>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct p
{
int xh;
int he;
};
p x[10000];
bool rule (p a,p b)
{
if (a.he==b.he)
return (a.xh<b.xh);
return (a.he<b.he);
}
int main (void)
{
int i,j,n,t,k;
while (scanf("%d",&n)==1)
{
if (n==0)
break;
for (i=0;i<n;++i)
{
scanf("%d",&x[i].xh);
x[i].he=0;
k=x[i].xh;
while (k!=0)
{
t=k%10;
x[i].he+=t*t;
k/=10;
}
}
sort(&x[0],&x[n],rule);
for (i=0;i<n-1;++i)
{
printf("%d ",x[i].xh);
}
printf("%d\n",x[i].xh);
}
return 0;
}