2010年7月2日 星期五

Problem 10664 Luggage,行李

此題讀入各行李重量後,以大到小排序,最後再平均分配在兩台車子上,如兩台車同重量,輸出 "YES",否則,輸出 "NO"。

此處我也用到了輸入優化的方式。
關鍵程式碼如下:
#define SIZE 21

int luggage[SIZE], changeLine, index;

int getInt()
{
char ch;
int n = 0;
changeLine = 0;
while( ch = getchar())
if(ch != ' ' && ch != '\n') break;
n = ch - 48;
while( ch = getchar())
{
if(ch == ' ' || ch == '\n') break;
n = n * 10 + ch - 48;
}
if (ch == '\n') changeLine = 1;
return n;
}

主程式內 ....
index = 0, changeLine = 0, a = 0, b = 0;
while (!changeLine)
{
luggage[index] = getInt();
for (i = index; i >= 1; i --)
if (luggage[i] > luggage[i - 1])
tmp = luggage[i], luggage[i] = luggage[i - 1], luggage[i - 1] = tmp;
else break;
index ++;
}

for (i = 0; i < index; i ++)
{
if (a == b) a += luggage[i];
else if (a > b) b += luggage[i];
else a += luggage[i];
}

if (a == b) puts("YES");
else puts("NO");

By David.K

p10664題目連結
回ACM題庫目錄
回首頁

沒有留言: