July 9, 2012
POJ 3253 Fence Repair

Farmer John wants to repair a small length of the fence around the pasture. He measures the fence and finds that he needs N (1 ≤ N ≤ 20,000) planks of wood, each having some integer length Li (1 ≤ Li ≤ 50,000) units. He then purchases a single long board just long enough to saw into the N planks (i.e., whose length is the sum of the lengths Li). FJ is ignoring the “kerf”, the extra length lost to sawdust when a sawcut is made; you should ignore it, too.FJ sadly realizes that he doesn’t own a saw with which to cut the wood, so he mosies over to Farmer Don’s Farm with this long board and politely asks if he may borrow a saw.Farmer Don, a closet capitalist, doesn’t lend FJ a saw but instead offers to charge Farmer John for each of the N-1 cuts in the plank. The charge to cut a piece of wood is exactly equal to its length. Cutting a plank of length 21 costs 21 cents.Farmer Don then lets Farmer John decide the order and locations to cut the plank. Help Farmer John determine the minimum amount of money he can spend to create the N planks. FJ knows that he can cut the board in various different orders which will result in different charges since the resulting intermediate planks are of different lengths.

Input

Line 1: One integer N, the number of planks 

Lines 2..N+1: Each line contains a single integer describing the length of a needed plank

Output

Line 1: One integer: the minimum amount of money he must spend to make N-1 cuts

アリ本の解答を参考にした。二分木で考えると良い。

自分の解法は値の大きいものから順に引いていけば、残るものは必然的に短いものだという考え方だったが、二分木で構成を考えると必ずしもそうではないことが確認できた。

正しい解法はこちら。

#include <stdio.h>
#define MAX_N	20000
typedef long long ll;

#define swap(a, b) do { int t = (a); (a) = (b); (b) = t; } while(0)

int N;
int L[MAX_N];

void solve(void) {
	ll ans = 0;
	int mii1 = 0;
	int mii2 = 1;
	int i, t;
	
	while (N > 1) {
		mii1 = 0, mii2 = 1;
		
		if (L[mii1] > L[mii2]) {
			swap(mii1, mii2);
		}
		
		for (i = 2; i < N; i++) {
			if (L[i] < L[mii1]) {
				mii2 = mii1;
				mii1 = i;
			} else if (L[i] < L[mii2]) {
				mii2 = i;
			}
		}
		
		t = L[mii1] + L[mii2];
		ans += t;
		
		if (mii1 == N-1) {
			swap(mii1, mii2);
		}
		L[mii1] = t;
		L[mii2] = L[N-1];
		N--;
	}
	
	printf("%lld\n", ans);
}

int main(void) {
	int i;
	scanf("%d", &N);
	for (i = 0; i < N; i++) {
		scanf("%d", L+i);
	}
	solve();
	return 0;
}

私の誤った解答はこちら。

#include <stdio.h>
#include <stdlib.h>
#define N	20000

int planks[N];
int n = 0;

int compare(const void* a, const void* b) {
	if (*(int*)a > *(int*)b) {
		return -1;
	} else if (*(int*)a < *(int*)b) {
		return 1;
	} else {
		return 0;
	}
}

int main(void) {
	int i, amount, result;
	if (1 == scanf("%d", &n)) {
		
		for (i = 0; i < n; i++) {
			scanf("%d", planks+i);
		}
		
		qsort(planks, n, sizeof(int), compare);
		
		for (i = 0, amount = 0; i < n; i++) {
			amount += planks[i];
		}
		
		for (i = 0, result = 0; i < n-1; i++) {
			result += amount;
			amount -= planks[i];
		}
		printf("%d\n", result);
	}
	return 0;
}

(Source: poj.org)

10:31pm  |   URL: http://tmblr.co/Zpn4KvO-BpvM
Filed under: POJ programming c 
July 6, 2012
POJ 3069 Saruman’s Army

Saruman the White must lead his army along a straight path from Isengard to Helm’s Deep. To keep track of his forces, Saruman distributes seeing stones, known as palantirs, among the troops. Each palantir has a maximum effective range of R units, and must be carried by some troop in the army (i.e., palantirs are not allowed to “free float” in mid-air). Help Saruman take control of Middle Earth by determining the minimum number of palantirs needed for Saruman to ensure that each of his minions is within R units of some palantir.

Input

The input test file will contain multiple cases. Each test case begins with a single line containing an integer R, the maximum effective range of all palantirs (where 0 ≤ R ≤ 1000), and an integer n, the number of troops in Saruman’s army (where 1 ≤ n ≤ 1000). The next line contains n integers, indicating the positions x1, …, xn of each troop (where 0 ≤ xi ≤ 1000). The end-of-file is marked by a test case with R = n = −1.

Output

For each test case, print a single integer indicating the minimum number of palantirs needed.

アリ本に解法が載っていたのでクリア後確認したが、構成はおおむね同じで一安心。

#include <stdio.h>
#include <stdlib.h>
#define ARMY	1000

int compare(const void* a, const void* b) {
	if (*(int*)a < *(int*)b) {
		return -1;
	} else if (*(int*)a > *(int*)b) {
		return 1;
	} else {
		return 0;
	}
}

int main(void) {
	int R, n, i, j, k, total;
	char buffer[16];
	int army[ARMY];
	while (fgets(buffer, sizeof(buffer)/sizeof(buffer[0]), stdin)) {
		if (2 == sscanf(buffer, "%d%d", &R, &n)) {
			if (-1 == R && -1 == n) {
				break;
			}
			for (i = 0; i < n; i++) {
				scanf("%d", army+i);
			}
			
			qsort(army, n, sizeof(int), compare);
			
			for (i = 0, total = 0; i < n; ) {
				j = 1;
				while (i+j < n && army[i+j] <= army[i]+R) {
					j++;
				}
				total++;
				j--;
				
				k = 1;
				while (i+j+k < n && army[i+j+k] <= army[i+j]+R) {
					k++;
				}
				i += j+k;
			}
			printf("%d\n", total);
			
			fgets(buffer, sizeof(buffer)/sizeof(buffer[0]), stdin);	// 読み捨て
			
		} else {
			break;
		}
	}
	return 0;
}

(Source: poj.org)

2:17am  |   URL: http://tmblr.co/Zpn4KvOlSuGi
  
Filed under: POJ programming c 
July 6, 2012
POJ 3617 Best Cow Line

FJ is about to take his N (1 ≤ N ≤ 2,000) cows to the annual”Farmer of the Year” competition. In this contest every farmer arranges his cows in a line and herds them past the judges.The contest organizers adopted a new registration scheme this year: simply register the initial letter of every cow in the order they will appear (i.e., If FJ takes Bessie, Sylvia, and Dora in that order he just registers BSD). After the registration phase ends, every group is judged in increasing lexicographic order according to the string of the initials of the cows’ names.FJ is very busy this year and has to hurry back to his farm, so he wants to be judged as early as possible. He decides to rearrange his cows, who have already lined up, before registering them.FJ marks a location for a new line of the competing cows. He then proceeds to marshal the cows from the old line to the new one by repeatedly sending either the first or last cow in the (remainder of the) original line to the end of the new line. When he’s finished, FJ takes his cows for registration in this new order.Given the initial order of his cows, determine the least lexicographic string of initials he can make this way.

Input

* Line 1: A single integer: N

* Lines 2..N+1: Line i+1 contains a single initial (‘A’..’Z’) of the cow in the ith position in the original line

Output

The least lexicographic string he can make. Every line (except perhaps the last one) contains the initials of 80 cows (‘A’..’Z’) in the new line.

英語が課題。Presentation Error(答えはあっているが出力フォーマットが異なる)に悩まされた。

#include <stdio.h>
#define N	2001

int main(void) {
	char buffer[8];
	char before[N] = {0}, after[N] = {0};
	int i, j, n;
	int l, r;
	fgets(buffer, sizeof(buffer)/sizeof(buffer[0]), stdin);
	if (1 == sscanf(buffer, "%d", &n)) {
		for (i = 0; i < n; i++) {
			fgets(buffer, sizeof(buffer)/sizeof(buffer[0]), stdin);
			before[i] = buffer[0];
		}
	}
	
	i = 0;
	l = 0;
	r = n-1;
	while (l < r) {
		if (before[l] == before[r]) {
			for (j = 0; before[l+j] == before[r-j] && l+j < r-j; j++);
			if (before[l+j] < before[r-j]) {
				after[i] = before[l++];
			} else {
				after[i] = before[r--];
			}
			
		} else if (before[l] < before[r]) {
			after[i] = before[l++];
		} else {
			after[i] = before[r--];
		}
		i++;
	}
	if (l == r) {
		after[i] = before[l];
	}
	
	i = 0;
	while (n > 80*(i+1)) {
		buffer[0] = after[80*(i+1)];
		after[80*(i+1)] = '\0';
		puts(after+80*i);
		after[80*(i+1)] = buffer[0];
		i++;
	}
	puts(after+80*i);
	return 0;
}

(Source: poj.org)

12:53am  |   URL: http://tmblr.co/Zpn4KvOlBZ4p
Filed under: POJ programming c 
July 5, 2012
迷路の最短路

【問題】

大きさがNxMの迷路が与えられます。迷路っは通路と壁からできており、1ターンに隣接する上下左右4マスへの通路へ移動することができます。スタートからゴールまで移動するのに必要な最小のターン数を求めなさい。ただし、スタートからゴールまで移動できると仮定します。

アリ本のサンプル(P37)。

そうそう、幅優先探索はキューを使うのだった。深さ優先探索で解こうとして解けなかった問題も、実は幅優先探索だと解けるかもしれない。ほかにも探索方法はいろいろあるしな。

#include <stdio.h>
#define N	10
#define NaN	1
#define GOAL	1

typedef struct {
	int x;
	int y;
	int total;
} Pos;

char past[N][N];
Pos que[N*N];
int count = 0;

char maze[N][N] = {"#S######.#",
		"......#..#",
		".#.##.##.#",
		".#........",
		"##.##.####",
		"....#....#",
		".#######.#",
		"....#.....",
		".####.###.",
		"....#...G#" };

int check(int x, int y, int total) {
	if (0 <= x && x < N && 0 <= y && y < N &&
		past[y][x] == NaN && (maze[y][x] == '.' || maze[y][x] == 'G')) {
		if (maze[y][x] == 'G') {
			return GOAL;
		}
		que[count%100].x = x;
		que[count%100].y = y;
		que[count%100].total = total;
		past[y][x] = 0;
		count++;
	}
	return !GOAL;
}

int main(void) {
	int i, x, y, total;
	
	for (y = 0; y < N; y++) {
		for (x = 0; x < N; x++) {
			que[y*10+x].x = que[y*10+x].y = NaN;
			past[y][x] = NaN;
		}
	}
	que[count  ].x = 1;
	que[count  ].y = 0;
	que[count++].total = 0;
	
	total = 0;
	while (total < count) {
		i = total % 100;
		x = que[i].x;
		y = que[i].y;
		
		if (GOAL == check(x, y-1, que[i].total+1) ||	// 上
		GOAL == check(x+1, y, que[i].total+1) ||	// 右
		GOAL == check(x, y+1, que[i].total+1) ||	// 下
		GOAL == check(x-1, y, que[i].total+1)) {	// 左
			break;
		}
		
		total++;
	}
	
	printf("%d\n", que[total%100].total+1);
	return 0;
}

10:32pm  |   URL: http://tmblr.co/Zpn4KvOkrZFs
Filed under: programming c 
May 25, 2012
AOJ 0502 Dice

問題と図はこちら。さいころを転がして目の数を合計する。

ある方向に転がった時に何点増えるか毎回設定した。

#include <stdio.h>

int North, South, West, East, Left, Right, Other;

void initialize(void) {
	North = 2, South = 5, West = 3, East = 4, Left = 1, Right = 1, Other = 6;
}

int dice(char n) {
	int temp;
	switch (n) {
	case 'N':
		n = North;
		North = Other;
		Other = South;
		South = Left;
		Left = Right = n;
		break;
	case 'S':
		n = South;
		South = Other;
		Other = North;
		North = Left;
		Left = Right = n;
		break;
	case 'W':
		n = West;
		West = Other;
		Other = East;
		East = Left;
		Left = Right = n;
		break;
	case 'E':
		n = East;
		East = Other;
		Other = West;
		West = Left;
		Left = Right = n;
		break;
	case 'L':
		n = Left;
		temp = North;
		North = East;
		East = South;
		South = West;
		West = temp;
		break;
	case 'R':
		n = Right;
		temp = North;
		North = West;
		West = South;
		South = East;
		East = temp;
		break;
	}
	return n;
}
int main(void) {
	char buffer[24];
	int i, n, amount;
	while (fgets(buffer, sizeof(buffer)/sizeof(buffer[0]), stdin)) {
		if (1 == sscanf(buffer, "%d", &n) && n) {
			amount = 1;
			initialize();
			for (i = 0; i < n; i++) {
				fgets(buffer, sizeof(buffer)/sizeof(buffer[0]), stdin);
				amount += dice(buffer[0]);
			}
			printf("%d\n", amount);
		} else {
			return 0;
		}
	}
	return 0;
}

7:14pm  |   URL: http://tmblr.co/Zpn4KvM6FaU1
Filed under: AOJ programming c 
May 25, 2012
AOJ 0104 Magic Tile

There is a magic room in a homestead. The room is paved with H × W tiles. There are five different tiles:

  • Tile with a east-pointing arrow
  • Tile with a west-pointing arrow
  • Tile with a south-pointing arrow
  • Tile with a north-pointing arrow
  • Tile with nothing

Once a person steps onto a tile which has an arrow, the mystic force makes the person go to the next tile pointed by the arrow. If the next tile has an arrow, the person moves to the next, ans so on. The person moves on until he/she steps onto a tile which does not have the arrow (the tile with nothing). The entrance of the room is at the northwest corner.

Your task is to write a program which simulates the movement of the person in the room. The program should read strings which represent the room and print the last position of the person.

The input represents the room as seen from directly above, and up, down, left and right side of the input correspond to north, south, west and east side of the room respectively. The horizontal axis represents x-axis (from 0 to W-1, inclusive) and the vertical axis represents y-axis (from 0 to H-1, inclusive). The upper left tile corresponds to (0, 0).

The following figure shows an example of the input:

10 10

»>v..»>v

…v..^..v

…»>^..v

………v

.v««…v

.v…^…v

.v…^««

.v……..

.v…^….

.»»^….

Characters represent tiles as follows:

‘>’: Tile with a east-pointing arrow

‘<’: Tile with a west-pointing arrow 

’^’: Tile with a north-pointing arrow 

‘v’: Tile with a south-pointing arrow 

’.’: Tile with nothing

If the person goes in cycles forever, your program should print “LOOP”. You may assume that the person never goes outside of the room.

楽勝。

#include <stdio.h>
#include <string.h>
#define MAX_N	108

char maze[MAX_N][MAX_N];

void solve(int height, int width) {
	int h, w;
	for (h = 0, w = 0; h < height && w < width; ) {
		switch (maze[h][w]) {
		case '\0':
			return;
		case '.':
			printf("%d %d\n", w, h);
			return;
		case '>':
			maze[h][w] = '-';
			w++;
			break;
		case '<':
			maze[h][w] = '-';
			w--;
			break;
		case '^':
			maze[h][w] = '-';
			h--;
			break;
		case 'v':
			maze[h][w] = '-';
			h++;
			break;
		case '-':
			printf("LOOP\n");
			return;
		}
	}
}

int main(void) {
	char buffer[128];
	int i, height, width;
	while (fgets(buffer, sizeof(buffer)/sizeof(buffer[0]), stdin)) {
		if (2 == sscanf(buffer, "%d%d", &height, &width) && !(!height && !width)) {
			memset(maze, 0x00, sizeof(maze));
			for (i = 0; i < height; i++) {
				fgets(maze[i], sizeof(maze[i])/sizeof(maze[i][0]), stdin);
			}
			solve(height, width);
		} else {
			return 0;
		}
	}
	return 0;
}

(Source: judge.u-aizu.ac.jp)

3:24pm  |   URL: http://tmblr.co/Zpn4KvM5y_CG
Filed under: AOJ programming c 
May 25, 2012
POJ 1002 487-3279

Businesses like to have memorable telephone numbers. One way to make a telephone number memorable is to have it spell a memorable word or phrase. For example, you can call the University of Waterloo by dialing the memorable TUT-GLOP. Sometimes only part of the number is used to spell a word. When you get back to your hotel tonight you can order a pizza from Gino’s by dialing 310-GINO. Another way to make a telephone number memorable is to group the digits in a memorable way. You could order your pizza from Pizza Hut by calling their “three tens” number 3-10-10-10. 

The standard form of a telephone number is seven decimal digits with a hyphen between the third and fourth digits (e.g. 888-1200). The keypad of a phone supplies the mapping of letters to numbers, as follows: 

A, B, and C map to 2 

D, E, and F map to 3 

G, H, and I map to 4 

J, K, and L map to 5 

M, N, and O map to 6 

P, R, and S map to 7 

T, U, and V map to 8 

W, X, and Y map to 9 

There is no mapping for Q or Z. Hyphens are not dialed, and can be added and removed as necessary. The standard form of TUT-GLOP is 888-4567, the standard form of 310-GINO is 310-4466, and the standard form of 3-10-10-10 is 310-1010. 

Two telephone numbers are equivalent if they have the same standard form. (They dial the same number.) 

Your company is compiling a directory of telephone numbers from local businesses. As part of the quality control process you want to check that no two (or more) businesses in the directory have the same telephone number. 

Input

The input will consist of one case. The first line of the input specifies the number of telephone numbers in the directory (up to 100,000) as a positive integer alone on the line. The remaining lines list the telephone numbers in the directory, with each number alone on a line. Each telephone number consists of a string composed of decimal digits, uppercase letters (excluding Q and Z) and hyphens. Exactly seven of the characters in the string will be digits or letters. 

Output

Generate a line of output for each telephone number that appears more than once in any form. The line should give the telephone number in standard form, followed by a space, followed by the number of times the telephone number appears in the directory. Arrange the output lines by telephone number in ascending lexicographical order. If there are no duplicates in the input print the line: 

No duplicates.

最初、数値の比較で昇順に並べ替えたが、辞書順に並べる必要があるためやり直した。挿入ソートはO(n^2)のためTLE。結局、データは単純に配列に保存していき、strcmpとqsortで辞書順に整列したあと出力時にに重複カウントすることで解決。

最後、どうしてもテストにパスしなかったのは、用意していた入力バッファのサイズがchar 20個分と少ないためだった。1データあたり何文字入力されるかは明示されていないことも多いが、”ある程度”は用意してあげなければならないらしい。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_DATA	100000

typedef struct {
	char data[8];
	int num;
} Number;

Number list[MAX_DATA];
int amount = 0;
char dict[256];

void initialize(void) {
	dict['0'] = 0;
	dict['1'] = 1;
	dict['2'] = dict['A'] = dict['B'] = dict['C'] = 2;
	dict['3'] = dict['D'] = dict['E'] = dict['F'] = 3;
	dict['4'] = dict['G'] = dict['H'] = dict['I'] = 4;
	dict['5'] = dict['J'] = dict['K'] = dict['L'] = 5;
	dict['6'] = dict['M'] = dict['N'] = dict['O'] = 6;
	dict['7'] = dict['P'] = dict['R'] = dict['S'] = 7;
	dict['8'] = dict['T'] = dict['U'] = dict['V'] = 8;
	dict['9'] = dict['W'] = dict['X'] = dict['Y'] = 9;
}

int compare(const void* data1, const void* data2) {
	return strcmp(((const char*)data1), ((const char*)data2));
}

void print(void) {
	char duplicated = 0;
	int i, j;
	
	qsort(list, amount, sizeof(Number), compare);
	
	for (i = 0, j = 1; i < amount; i+=j) {
		j = 1;
		while (list[i].num == list[i+j].num) {
			j++;
		}
		if (j > 1) {
			printf("%c%c%c-%c%c%c%c %d\n",
				list[i].data[0],list[i].data[1],list[i].data[2],list[i].data[3],
				list[i].data[4],list[i].data[5],list[i].data[6], j);
			duplicated = 1;
		}
	}
	if (!duplicated) {
		printf("No duplicates.\n");
	}
}

int main(void) {
	int i, j, k, l, n;
	char buffer[256];
	
	initialize();
	fgets(buffer, sizeof(buffer)/sizeof(buffer[0]), stdin);
	if (1 == sscanf(buffer, "%d", &n)) {
		for (i = 0; i < n; i++) {
			fgets(buffer, sizeof(buffer)/sizeof(buffer[0]), stdin);
			j = k = l = 0;
			while (buffer[j] != '\0') {
				if (('0' <= buffer[j] && buffer[j] <= '9') ||
					('A' <= buffer[j] && buffer[j] <= 'Y' && buffer[j] != 'Q')) {
					list[amount].data[l++] = '0' + dict[(int)buffer[j]];
					k = k * 10 + (int)dict[(int)buffer[j]];
				}
				j++;
			}
			list[amount++].num = k;
		}
		print();
	}
	
	return 0;
}

(Source: poj.org)

9:39am  |   URL: http://tmblr.co/Zpn4KvM4sh05
  
Filed under: POJ programming c 
May 24, 2012
POJ 1001 Exponentiation

Problems involving the computation of exact values of very large magnitude and precision are common. For example, the computation of the national debt is a taxing experience for many computer systems. This problem requires that you write a program to compute the exact value of Rn where R is a real number ( 0.0 < R < 99.999 ) and n is an integer such that 0 < n <= 25.

Input

The input will consist of a set of pairs of values for R and n. The R value will occupy columns 1 through 6, and the n value will be in columns 8 and 9.

Output

The output will consist of one line for each line of input giving the exact value of R^n. Leading zeros should be suppressed in the output. Insignificant trailing zeros must not be printed. Don’t print the decimal point if the result is an integer.

数字を逆順にchar配列に入れると操作しやすい。

#include <stdio.h>
#include <string.h>
#define DIGIT	200

char output[DIGIT];
char R[8];
int point;

void set_number(void) {
	int i = 0, j = 0;
	char temp;
	point = 5;
	// remove prefix
	while (R[i] != '\0' && R[i] == '0') {
		i++;
	}
	while (i) {
		if (R[i] != '\0') {
			R[j++] = R[i++];
		} else {
			R[j] = '\0';
			point -= i-j;
			break;
		}
	}
	i = 0;
	while (R[i] != '\0' && R[i] != '.') {
		i++;
		point--;
	}
	while (R[i] != '\0') {
		R[i] = R[i+1];
		i++;
	}
	i--;	// R[i] == '\0';
	if (5 == point) {
		point = 0;
	}
	// R->reverse && copy to output
	for (j = 0, output[i] = R[i], --i; j <= i/2; j++) {
		output[i-j] = R[j];
		temp = R[i-j];
		R[i-j] = R[j];
		output[j] = R[j] = temp;
	}
}

void calc(int n) {
	char work[DIGIT] = {0};
	int i = 0, j;
	int temp = 0;
	if (--n <= 0) {
		return;
	}
	for (j = 0; R[j] != '\0'; j++) {
		for (i = 0, temp = 0; output[i] != '\0'; i++) {
			temp += (output[i]-'0') * (R[j]-'0');
			temp += (work[i+j] != 0) ? work[i+j]-'0' : 0;
			work[i+j] = (temp % 10) + '0';
			temp /= 10;
		}
		while (temp) {
			temp += (work[i+j] != 0) ? work[i+j]-'0' : 0;
			work[j+i++] = (temp % 10) + '0';
			temp /= 10;
		}
	}
	strcpy(output, work);
	calc(n);
}

void print(void) {
	int i, temp;
	
	if (point > 0) {
		for (i = 0; i < point && output[i] == '0'; i++);
		output[i-1] = '-';
	}
	
	i = strlen(output)-1;
	if (point > i) {
		putchar('.');
		temp = point;
		while (--temp > i) {
			putchar('0');
		}
	}
	
	while (i >= 0 && output[i] != '-') {
		putchar(output[i]);
		if (i == point && output[i-1] != '-') {
			putchar('.');
		}
		i--;
	}
	putchar('\n');
}

int main(void) {
	char buffer[32];
	int n;
	while (fgets(buffer, sizeof(buffer)/sizeof(buffer[0]), stdin)) {
		if (2 == sscanf(buffer, "%s %d", R, &n)) {
			memset(output, 0x00, sizeof(output));
			set_number();
			point *= n;
			calc(n);
			print();
		}
	}
	return 0;
}

(Source: poj.org)

9:31am  |   URL: http://tmblr.co/Zpn4KvM16ycU
Filed under: POJ programming c 
May 23, 2012
AOJ 0501 Data Conversion

与えられた変換表にもとづき,データを変換するプログラムを作成しなさい.

データに使われている文字は英字か数字で,英字は大文字と小文字を区別する.変換表に現れる文字の順序に規則性はない.

変換表は空白をはさんで前と後ろの 2 つの文字がある(文字列ではない).変換方法は,変換表のある行の前の文字がデータに現れたら,そのたびにその文字を後ろの文字に変換し出力する.変換は 1 度だけで,変換した文字がまた変換対象の文字になっても変換しない.変換表に現れない文字は変換せず,そのまま出力する.

入力ファイルには,変換表(最初の n + 1 行)に続き変換するデータ(n + 2 行目以降)が書いてある. 1 行目に変換表の行数 n,続く n 行の各行は,空白をはさんで 2 つの文字,さらに続けて, n + 2 行目に変換するデータの行数 m,続く m 行の各行は 1 文字である. m < 108 とする.出力は,出力例のように途中に空白や改行は入れず 1 行とせよ.

アップロードする出力ファイルにおいては,出力(変換後の文字列)の後に改行を入れること.

もっと簡単に書いてたんだけど、なぜかテストクリアできない。なんだかテストデータに余計な空白文字が入ってる感じ…ctype.hをつかって正しく英数字だけを取り扱うようにしてみたらテストクリア。

#include <stdio.h>
#include <ctype.h>
#define MAX		256

int main(void) {
	char list[MAX];
	char buffer[8];
	char key, value;
	int i, n;
	while (fgets(buffer, sizeof(buffer)/sizeof(buffer[0]), stdin)) {
		if (1 == sscanf(buffer, "%d", &n)) {
			if (!n) {
				return 0;
			}
			for (i = 0; i < MAX; i++) {
				list[i] = i;
			}
			for (i = 0; i < n; i++) {
				fgets(buffer, sizeof(buffer)/sizeof(buffer[0]), stdin);
				if (2 == sscanf(buffer, "%c %c", &key, &value)) {
					list[(int)key] = value;
				}
			}
			while (fgets(buffer, sizeof(buffer)/sizeof(buffer[0]), stdin) && 1 != sscanf(buffer, "%d", &n));
			for (i = 0; i < n; ) {
				fgets(buffer, sizeof(buffer)/sizeof(buffer[0]), stdin);
				if (isalnum((int)buffer[0])) {
					putchar(list[(int)buffer[0]]);
					i++;
				}
			}
			putchar('\n');
		}
	}
	return 0;
}

(Source: judge.u-aizu.ac.jp)

2:02am  |   URL: http://tmblr.co/Zpn4KvLxiN4K
Filed under: AOJ programming c 
May 23, 2012
POJ 1000 A+B Problem

Calculate a+b

おなじみの。

#include <stdio.h>

int main(void) {
	char buffer[8];
	int a, b;
	fgets(buffer, sizeof(buffer)/sizeof(buffer[0]), stdin);
	if (2 == sscanf(buffer, "%d%d", &a, &b)) {
		printf("%d\n", a+b);
	}
	return 0;
}

(Source: poj.org)

12:23am  |   URL: http://tmblr.co/Zpn4KvLxTp3e
Filed under: POJ programming c