POJ 4011 Automated Telephone Exchange 解析

http://poj.org/problem?id=4011

Problem A. Automated Telephone Exchange
Input file: ate.in
Output file: ate.out
Time limit: 3 seconds
Memory limit: 256 megabytes
In St Petersburg phone numbers are formatted as “XXX–XX–XX”, where the first three digits represent
index of the Automated Telephone Exchange (ATE). Each ATE has exactly 10 000 unique phone numbers.
Peter has just bought a new flat and now he wants to install a telephone line. He thinks that a phone
number is lucky if the arithmetic expression represented by that phone number is equal to zero. For
example, the phone number 102–40–62 is lucky (102 - 40 - 62 = 0), and the number 157–10–47 is not
lucky (157 -10 - 47 = 100 6= 0).
Peter knows the index of the ATE that serves his house. To get an idea of his chances to get a lucky
number he wants to know how many lucky numbers his ATE has.
Input
The input file contains a single integer number n — the index of Peter’s ATE (100 <= n <=  999).
Output
Output a single integer number — the number of lucky phone numbers Peter’s ATE has.
Examples
ate.in ate.out
196        3
239        0

這是一道求解線性不定方程組的題目。我的思路如下:

         x + y =n

        0 <= x <= 99

        0 <= y <= 99   => 0<=n-x<=99 =>  n-99 <= x <=n

        因此,  本題答案 = 區間 [ n-99, 99] 的長度 ,顯然 n-99<=99 ,即 n <=198 ,該方程組纔有解。分析到這裏,下面的代碼就很容易寫出來了:

#include"stdio.h"
int main()
{

	FILE *fp1=fopen("ate.in","r");
	FILE *fp2=fopen("ate.out","w");
	int n;
	while(!feof(fp1))
	{
		fscanf(fp1,"%d",&n);
		if(n>=199)
			fprintf(fp2,"0\n");
		else
			fprintf(fp2,"%d\n",199-n);
	}
	fclose(fp1);
	fclose(fp2);
	
	return 0;
}

         

          但是,提交以後是WA,看了discuss才知道此題還是控制檯輸入輸出,壓根就不是文件輸入輸出,題目誤導人啊~,將輸入輸出稍作修改得到:

#include"stdio.h"
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		if(n>=199)
			printf("0\n");
		else
			printf("%d\n",199-n);
	}
	return 0;
}
          
75 11739694 yinjili 164K 16MS C++ 160B 2013-07-06 19:58:59

           耗時16MS,在C++中排名第75。

           因爲我看到有人耗時爲0MS,所以我嘗試改進代碼。首先,我想到打表,代碼如下:

#include"stdio.h"
int main()
{
	int a[1000]={0};
	int i;
	a[198]=1;
	for(i=197;i>=100;i--)
		a[i]=a[i+1]+1;
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		printf("%d\n",a[n]);
	}
	return 0;
}

yinjili 4011 Accepted 164K 63MS C++ 202B

          耗時63MS。

          我發現n>=199和199-n操作有點相似,考慮將其合爲一個操作,並將199用16進製表示,因爲整數在計算機中以二進制形式存儲,二進制和16進制轉換要快一點。

          改進後的代碼如下:

#include"stdio.h"
int main()
{
	int n,t;
	while(scanf("%d",&n)!=EOF)
	{
		t=0xC7-n;
		printf("%d\n",t>0? t:0);
	}
	return 0;
}

yinjili 4011 Accepted 164K 0MS C++ 136B
7 11740030(3) yinjili 164K 0MS C++ 136B 2013-07-06 21:47:04

   耗時0MS,在C++中排名第7。

   

          嘗試改善代碼,提高性能,不僅僅滿足AC !

   



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章